Benchmarking Zero-Cost Abstraction in Rust
Benchmarking and Comparing functions with and without functions in Rust Programming.
Rust is the future of Systems Programming because of some of its features, which make a program performant. One of the key features is Zero-Cost abstraction, which means you can write code at a high level of abstraction without sacrificing performance.
Want to implement a routing table with exact matching and longest prefix matching? Check out my previous posts.
“Zero-Cost Abstraction” was something I came across multiple times while I read blogs on Rust programming. Although I knew what it meant at a very high level, I never explored it deeply.
So instead of explaining what it means and how it works let’s do a simple experiment and draw conclusions.
Functions With and Without Abstractions
The experiment consists of two functions. Firstly, a function with no abstraction. Second, a function with abstraction.
Since we are comparing the performance, both functions must do the same thing. The snippet below shows a function which calculates the sum of the squares of the elements in the vector using a for loop to iterate over the elements.
However, in the snippet below the function calculates the sum of squares but using methods called on the vector object. Which is the abstraction we are talking about. In other languages, it is seen that abstraction can cause additional overhead but NOT IN RUST (at least that’s what they claim).
Benchmarking
Let’s verify this claim using the Rust benchmarking feature and the criterion crate. The benchmark_function runs the functions we need to benchmark multiple times and provides us with some stats.
If you want some content on Benchmarking in Rust then Comment below.
On running the benchmarking tests using the cargo bench command.
From the above snippet, we can observe that both functions perform similarly. The amount of time taken and outliers are more or less the same. no_abstraction does perform slightly better (which is obvious).
However, as I completed this experiment I realized that having a comparison between Rust and other languages such as Go, C++ or even JavaScript might be a good way to understand if Zero-Cost Abstraction is useful.
If you are looking for the full source code: Zero_cost_abstraction
Follow me on LinkedIn: anvayabn
Also if you would like to collaborate and learn DM me on Substack.





