thecodex.expert · The Codex Family of Knowledge
Rust

Performance and Memory

Rust's own documentation makes a direct claim most languages wouldn't dare: a hand-written low-level loop and an idiomatic iterator chain compile to the SAME machine code.

Rust 1.96 Zero-cost abstractions Last verified:
Canonical Definition

Zero-cost abstraction, a principle Rust inherited from C++ and applies pervasively, means using a high-level feature (an iterator chain, a generic function, a closure) produces the same machine code as if you had hand-written the low-level equivalent yourself — you don't pay a performance penalty for writing more readable, more abstract code. Combined with no garbage collector (memory is freed deterministically when its owner goes out of scope) and no runtime type checks that a monomorphized generic would otherwise need, Rust routinely benchmarks within a few percent of equivalent C or C++ code.

Iterators compile to the same code as a manual loop

The Rust Book makes this comparison directly: an idiomatic, readable iterator chain and a hand-rolled indexed loop doing the identical work compile to statistically indistinguishable assembly — there is no abstraction tax for choosing the more expressive style.

Rustiterator_vs_loop.rs
// idiomatic — reads clearly
let sum: i32 = (1..=1000).filter(|n| n % 3 == 0).sum();

// manual — same performance, more error-prone to write correctly
let mut sum2 = 0;
for n in 1..=1000 {
    if n % 3 == 0 {
        sum2 += n;
    }
}

Deterministic memory, no garbage collector pauses

Because ownership determines exactly when a value is dropped (at the end of its owner's scope, verified at compile time), there's no garbage collector, no unpredictable collection pause, and no runtime memory-management overhead at all — the cleanup code is inserted directly into the compiled binary at the precise point it's needed.

Rustdeterministic_drop.rs
{
    let data = vec![1, 2, 3];   // allocated here
    // ... use data ...
}   // data is deallocated HERE, deterministically, no GC involved

Benchmarking with criterion

The standard library's built-in benchmarking (#[bench]) is nightly-only; the community standard is the criterion crate, which runs statistically rigorous benchmarks on stable Rust and reports confidence intervals rather than a single noisy number.

Rustbenches/my_benchmark.rs
use criterion::{criterion_group, criterion_main, Criterion};

fn bench_sum(c: &mut Criterion) {
    c.bench_function("sum 1000", |b| {
        b.iter(|| (1..=1000).filter(|n| n % 3 == 0).sum::<i32>())
    });
}

criterion_group!(benches, bench_sum);
criterion_main!(benches);

Sources

1
The Rust Project. The Rust Programming Language, "Comparing Performance: Loops vs. Iterators", doc.rust-lang.org/book/ch13-04, and the Criterion.rs documentation.