Performance Patterns
Preallocate Vector
Reserve Expected Space
When a program knows the expected number of items, reserving capacity avoids repeated growth work.
Program
Play the program to choose extra capacity and watch the vector keep length and capacity separate.
preallocate_vector.rs
fn main() {
let extra = ;
let mut items = Vec::with_capacity(3 + extra);
items.push("parse");
items.push("trace");
items.push("replay");
println!("len={} capacity={}", items.len(), items.capacity());
}
fn main() {
let extra = ;
let mut items = Vec::with_capacity(3 + extra);
items.push("parse");
items.push("trace");
items.push("replay");
println!("len={} capacity={}", items.len(), items.capacity());
}
fn main() {
let extra = ;
let mut items = Vec::with_capacity(3 + extra);
items.push("parse");
items.push("trace");
items.push("replay");
println!("len={} capacity={}", items.len(), items.capacity());
}
capacity
`Vec::with_capacity` reserves storage without changing the vector length.
growth
Choosing enough capacity up front avoids extra reallocations while pushing known items.
length
`len` counts initialized elements; `capacity` counts reserved slots.