Memory and Performance
Zero-cost abstractions, memory layout and niche optimization, allocation, benchmarking and profiling.
9 questions
JuniorTheoryCommonWhat differs between debug and release builds, and which one do you benchmark?
What differs between debug and release builds, and which one do you benchmark?
cargo build uses the dev profile: no optimizations, debug assertions and overflow panics on. --release uses opt-level = 3 with both checks off, so overflow wraps. Debug code can be ten times slower: benchmark release.
Common mistakes
- ✗Drawing conclusions about the speed of iterators from a debug-build measurement
- ✗Expecting integer overflow to panic in release, though it wraps there unless
overflow-checksis turned on - ✗Thinking
debug_assert!runs in a release build, though onlyassert!does
Follow-up questions
- →How do you keep overflow checks in a release build, and what do they cost?
- →Why does
cargo testbuild without optimizations, and when would you pass--release?
MiddlePerformanceCommonWhat do zero-cost abstractions mean in Rust, and where does the promise break?
What do zero-cost abstractions mean in Rust, and where does the promise break?
No run-time cost over hand-written code, not no cost: iterators, closures, generics and newtypes compile to the same loop in release. The price is build time and binary size; it fails in debug builds and for dyn, Rc or RefCell.
Common mistakes
- ✗Reading zero cost as free, though it means parity with equivalent hand-written code
- ✗Proving that iterators are slow with a measurement taken in a debug build
- ✗Counting
dyn,Rc,ArcandRefCellas zero-cost, though each pays at run time
Follow-up questions
- →Why can an iterator over a slice skip the bounds checks that
v[i]in a loop may pay? - →How does monomorphization turn a zero-cost generic into longer builds and a bigger binary?
JuniorTheoryOccasionalWhich everyday operations allocate on the heap, and what does size_of show?
Which everyday operations allocate on the heap, and what does size_of show?
String::from, vec!, Box::new, to_string, format! and clone of a String allocate; references, &str, arrays and Vec::new() do not. size_of gives the stack size: i32 is 4, &T 8, String 24.
Common mistakes
- ✗Thinking
cloneof aStringshares the buffer, though it allocates a new copy of the text - ✗Reading
size_of::<String>()as the size of the text, though it is only the 24-byte header on the stack - ✗Assuming
Vec::new()allocates, though the buffer appears only with the first element
Follow-up questions
- →Why is
&str16 bytes while&Stringis 8? - →How can you count the allocations a piece of code makes without third-party tools?
MiddlePerformanceOccasionalWhy is Option<&T> the size of a pointer while Option<u32> takes 8 bytes?
Why is Option<&T> the size of a pointer while Option<u32> takes 8 bytes?
A niche is a bit pattern a type never uses: null for &T and Box<T>, zero for NonZero<u32>. None lives there, so no tag is needed: 8, 8 and 4 bytes. u32 uses every pattern, so Option<u32> adds a tag and padding.
Common mistakes
- ✗Thinking
Option<T>is always bigger thanT, though references,BoxandNonZerokeep the size - ✗Expecting a niche in
u32,f64or a raw*const T, which allow every bit pattern - ✗Treating the size of
Option<String>as guaranteed, though only the types listed in thestd::optiondocs are
Follow-up questions
- →Why is
Option<*const u8>16 bytes whileOption<NonNull<u8>>is 8? - →Why can code using the foreign function interface
FFIpassOption<&T>to C as a nullable pointer?
MiddlePerformanceOccasionalA Rust program allocates and clones too much: how do you find and fix it?
A Rust program allocates and clones too much: how do you find and fix it?
A heap profiler like heaptrack or dhat first shows which lines allocate most. Then cut waste: &str and &[T] parameters, no clone or format! in hot loops, with_capacity, buffer reuse, a flat Vec over Vec<Vec<T>>.
Common mistakes
- ✗Optimizing by reading the code instead of measuring with a heap profiler first
- ✗Taking
StringorVec<T>parameters where&stror&[T]would do, forcing callers to clone - ✗Expecting a release build to remove
clonecalls, though each one still copies the data
Follow-up questions
- →When does the clone-on-write type
Cow<str>save an allocation, and when does it not? - →Why does a flat
Vec<T>with index math beatVec<Vec<T>>for a grid?
SeniorPerformanceOccasionalWhat does monomorphization cost, and how do you limit it in a generic API?
What does monomorphization cost, and how do you limit it in a generic API?
Every type gets its own copy of a generic function: longer builds, a bigger binary, i-cache pressure. Limit it with a thin generic shell over a non-generic inner function, dyn Trait on cold paths, impl Into<String> only where it pays.
Common mistakes
- ✗Calling generics free, forgetting the build time and binary size that each instantiation adds
- ✗Making a large function generic over
AsRef<Path>orInto<String>, so its whole body is copied per argument type - ✗Ruling out
dyn Traiteverywhere, though on a cold boundary it costs little and saves copies
Follow-up questions
- →Why do generic std APIs that take
AsRef<Path>usually forward to a non-generic inner function? - →How would you find which generic functions bloat a binary with the size-analysis tool
cargo bloat?
SeniorPerformanceOccasionalHow do you find and fix a performance problem in Rust without guessing?
How do you find and fix a performance problem in Rust without guessing?
Profile a release build with debug = true using perf and a flamegraph to see where time goes, record a baseline with a criterion benchmark, change one thing, and keep it only if a second run shows a real, repeatable gain.
Common mistakes
- ✗Profiling or timing a debug build, whose hot spots differ from the release build's
- ✗Thinking
debug = truein[profile.release]slows the code, though it only adds symbols - ✗Declaring a change faster after one run, without repetitions or a confidence interval
Follow-up questions
- →Why does a benchmark without
std::hint::black_boxsometimes report0ns? - →How would you catch a speed regression in continuous integration
CIwith the benchmarking cratecriterion?
SeniorPerformanceOccasionalWhich release-profile settings speed up a Rust binary, and what does each cost?
Which release-profile settings speed up a Rust binary, and what does each cost?
lto = "fat" and codegen-units = 1 let LLVM optimize across crates and units but slow builds a lot; panic = "abort" shrinks code but skips unwinding and Drop; PGO needs a training run; target-cpu=native gives up portability.
Common mistakes
- ✗Expecting
panic = "abort"to run destructors and allowcatch_unwind, though the process simply aborts - ✗Shipping a binary built with
target-cpu=nativeto machines with older CPUs - ✗Turning on every setting without measuring, and paying with slow builds for no gain
Follow-up questions
- →How does profile-guided optimization
PGOwork with-Cprofile-generateand-Cprofile-use? - →When would you choose
opt-level = "s"or"z"over3?
SeniorPerformanceOccasionalHow does Rust lay out a struct in memory, and how do you shrink a hot one?
How does Rust lay out a struct in memory, and how do you shrink a hot one?
By default the compiler may reorder fields to cut padding: u8, u32, u16 fits in 8 bytes; #[repr(C)] keeps declared order, 12. To shrink, sort fields large to small, use smaller types or NonZero, box rare big parts.
Common mistakes
- ✗Assuming fields sit in declaration order without
#[repr(C)] - ✗Forgetting padding and tail rounding:
#[repr(C)]withu8,u32,u16takes 12 bytes, not 7 - ✗Reaching for
#[repr(packed)], whose fields cannot even be borrowed (E0793)
Follow-up questions
- →Why does one large, rarely used enum variant make every value bigger, and how does
Boxhelp? - →How do
size_of,align_ofandoffset_of!let you pin a layout in a test?