Cargo bench is faster than a release build because it compiles with optimizations that favor benchmark accuracy, not raw runtime speed, and it skips the debug assertions and overflow checks that slow down release binaries. Specifically, cargo bench uses the bench profile, which defaults to opt-level = 3 (same as release) but disables debug assertions and enables the test harness, allowing the compiler to inline and optimize code more aggressively while avoiding the safety checks that release keeps. This makes benchmark binaries run faster than release binaries, which is counterintuitive but deliberate: benchmarks measure performance, so they strip away everything that isn't needed for measurement.
What Cargo Profiles Actually Control
Cargo uses profiles to define compiler settings for different build modes. The three built-in profiles are dev (default for cargo build), release (for cargo build --release), and test (for cargo test). cargo bench does not use the release profile—it uses the bench profile, which is a separate configuration that inherits from release but overrides several key settings.
Here are the default differences that matter:
- opt-level: Both
releaseandbenchdefault to3(full optimization). So optimization level is not the reason for the speed difference. - debug-assertions:
releasedefaults tofalse, butbenchalso defaults tofalse. So that’s not the difference either. - overflow-checks:
releasedefaults tofalse,benchdefaults tofalse. Again, not the difference. - test: This is the key.
benchsetstest = true, which tells the compiler to include the test harness. This enables the#[bench]attribute and links the benchmark runner, but it also changes how the compiler treats the crate—it may inline functions more aggressively because it knows the binary is for testing, not for distribution.
But the real speed difference comes from something else: the benchmark harness itself. When you run cargo bench, the code that actually executes is the benchmark function, which is compiled with optimizations but also with the test harness that runs each benchmark in a loop. That loop is not the same as a release binary’s main function. The benchmark harness uses a timing loop that calls the function repeatedly, and the compiler can optimize that loop more aggressively because it knows the function is pure (no side effects) and can be inlined.
The Benchmark Harness and Its Optimizations
Rust’s built-in benchmark harness (from the test crate) works by running a function many times and measuring the elapsed time. To get accurate measurements, the harness uses a black box to prevent the compiler from optimizing away the function call if the result is unused. But the harness also allows the compiler to inline the function into the timing loop, which can eliminate function call overhead entirely.
In a release binary, the compiler must preserve the program’s observable behavior, including side effects like I/O, system calls, and global state changes. In a benchmark, the harness tells the compiler that the function is being measured, so it can assume the function is pure (no side effects) and optimize accordingly. This is why a benchmark binary can run faster than a release binary: the compiler is allowed to make more aggressive assumptions.
For example, if you write a benchmark that sums a vector, the compiler might unroll the loop, vectorize it, and even precompute the result if the input is constant. In a release binary, the same code might have to actually perform the loop because the input could change at runtime. The benchmark harness’s black box prevents the compiler from removing the computation entirely, but it still allows optimizations that a release build would not risk.
Why Release Builds Are Slower (and Why That’s Okay)
Release builds are designed for production use, not for measurement. They must be correct, safe, and stable. That means they include runtime checks that benchmarks can skip:
- Integer overflow checks: In debug builds, overflow panics; in release, overflow wraps silently by default. But even in release, the compiler may insert checks in some cases (e.g., when using certain standard library functions). Benchmarks can skip these because the harness assumes the code is correct.
- Bounds checks: The compiler inserts bounds checks for array indexing. In release, these are often elided if the compiler can prove the index is in range, but in benchmarks, the harness may provide hints (like constant indices) that make elision easier.
- Panic handling: Release binaries include panic unwinding code. Benchmarks can disable unwinding (via
panic = "abort") to reduce overhead, though that’s not the default.
But the biggest factor is that release binaries are compiled for the general case, while benchmarks are compiled for the specific case of running a tight loop. The compiler can specialize the benchmark code to the exact input and environment, which is not possible in a general-purpose binary.
Concrete Example: A Sum Function
Consider a simple function that sums a slice of integers:
fn sum(xs: &[i64]) -> i64 { xs.iter().sum() }
In a release build, this compiles to a loop that reads each element and adds it to an accumulator. The compiler might vectorize it (use SIMD) if it can prove alignment, but it must handle any length and any memory location.
In a benchmark, the harness might call sum with a fixed array of 1000 elements. The compiler can see that the length is constant, so it can fully unroll the loop (if the array is inlined) or at least eliminate the length check. It might also know that the array is immutable, so it can load all values into registers at once. This can make the benchmark loop run much faster than a release binary that has to handle arbitrary inputs.
This is why benchmark results often show higher throughput than real-world usage: the benchmark is measuring the best-case performance, not the typical case.
How to See the Difference Yourself
If you want to confirm this, you can create a simple Rust project with a benchmark and compare the assembly or run times. Here’s a step-by-step:
- Create a new project:
cargo new bench_test. - Add a
#[bench]function insrc/lib.rs(requires nightly Rust for the built-in benchmark harness). - Run
cargo benchand note the time. - Write a
mainfunction that calls the same function in a loop, compile withcargo build --release, and time it. - You’ll likely see the benchmark run faster, especially if the function is small and hot.
But note: the built-in benchmark harness is only available on nightly Rust. On stable, you’d use a crate like criterion, which has its own harness and may produce different results because it uses different measurement strategies (e.g., more sophisticated black boxes).
Common Misconception: Benchmarks Are “More Optimized”
People often think that cargo bench uses a higher optimization level than release. That’s false—both use opt-level = 3 by default. The difference is not the optimization level but the assumptions the compiler can make. Benchmarks are allowed to assume the code is pure and that the input is fixed, which enables optimizations that would be unsafe in a general binary.
Another misconception is that release builds are “slower” in an absolute sense. They are not—they are just slower than benchmarks for the same code, because they have to do more work. In practice, a release binary is usually fast enough for production, and the overhead is negligible compared to I/O or network latency.
When to Use Each Build Type
You should use cargo bench when you are measuring performance of a specific function or algorithm in isolation, under controlled conditions. It’s useful for micro-optimizations and for regression testing (comparing performance across commits).
You should use cargo build --release when you are shipping a binary to users. It’s the version that will actually run in production, so it must be correct and safe, not just fast.
If you want to measure real-world performance, you should benchmark the release binary itself, not the benchmark harness. Tools like hyperfine can time a release binary’s execution, which gives a more realistic picture.
Frequently Asked Questions
Is cargo bench always faster than cargo build --release?
No. It depends on the code. For small, pure functions that are called in a tight loop, the benchmark harness can be significantly faster. For larger programs with I/O or complex control flow, the difference is negligible or even reversed, because the benchmark harness adds overhead for measurement.
Does cargo bench use a different compiler than release?
No, it uses the same compiler (rustc) and the same optimization level. The difference is in the profile settings and the harness.
Can I make release builds as fast as benchmarks?
Sometimes. You can add [profile.release] settings like lto = true (link-time optimization) or codegen-units = 1 to improve optimization, but you cannot eliminate the safety checks that release binaries need. Benchmarks can also be made more realistic by using a harness like criterion that mimics real-world usage.
Why do benchmarks sometimes show faster times than the actual program?
Because benchmarks measure a synthetic scenario: a fixed input, a tight loop, and no external interference. Real programs have variable inputs, memory allocation, and system calls, which add overhead.
Is it safe to ship a binary compiled with the bench profile?
No. The bench profile includes the test harness, which is not intended for production. It also disables some safety checks (like overflow checks) that release keeps. Always ship a release build.
How do I set up benchmarks on stable Rust?
Stable Rust does not have the built-in benchmark harness. Use the criterion crate, which works on stable and provides more robust measurements.