Measure the work that matters.
Distinguish algorithmic costs, allocation, and build configuration.
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.
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);
}[0, 1, 4, 9]
- 1
with_capacity can avoid growth reallocations for this known size.
- 2
Length remains zero until elements are pushed.
- 3
Use cargo run --release for representative optimized application measurements.
cargo run -p lesson_performance03 Mind the boundary
04 Your next build
Replace repeated String allocation with a single preallocated buffer for a small report.
Reveal one possible solution +
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
What should you measure for application performance?
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.