Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ DESIGN, SAFETY & SHIPPING
BUILD NOTE 51 / 53

Measure the work that matters.

Distinguish algorithmic costs, allocation, and build configuration.

BY NAVAN SAMI◷ 9 MIN READADVANCEDRUST 2024

01 Understand the contract

Start performance work by choosing a representative workload and measuring an optimized build. Debug builds can exaggerate costs that optimization removes. Algorithmic complexity, allocation patterns, unnecessary copies, and I/O often matter more than a clever local expression. Reserve capacity when the final size is known and useful, but do not treat capacity as correctness. Instant measures elapsed time on a monotonic clock; one tiny timing is not a reliable benchmark. Use repeatable benchmarks and compare identical semantics before accepting an optimization.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/performance/src/main.rs
fn main() {
    let mut output = Vec::with_capacity(4);
    for n in 0..4 {
        output.push(n * n);
    }
    println!("{output:?}");
    assert_eq!(output.len(), 4);
}
↳ EXPECTED OUTPUT
[0, 1, 4, 9]
  1. 1

    with_capacity can avoid growth reallocations for this known size.

  2. 2

    Length remains zero until elements are pushed.

  3. 3

    Use cargo run --release for representative optimized application measurements.

From the extracted rust-workbench folder
cargo run -p lesson_performance

03 Mind the boundary

04 Your next build

A SMALL MISSION

Replace repeated String allocation with a single preallocated buffer for a small report.

Reveal one possible solution +
solutions/performance/src/main.rs
fn main() {
    let mut report = String::with_capacity(32);
    for name in ["build", "test"] {
        report.push_str(name);
        report.push('\n');
    }
    assert_eq!(report, "build\ntest\n");
}

05 Check your reasoning

QUICK SIGNAL CHECK

What should you measure for application performance?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.