What does push do when a Vec is full, and when should you reserve up front?
When len == capacity, push allocates a bigger buffer, moves every element and frees the old one: O(n) once, amortized O(1), as capacity doubles (Vec<i32>: 0, 4, 8, 16). with_capacity/reserve avoid it; shrink_to_fit frees spare room.
- Calling every
pushO(1), when one that reallocates costs O(n) and only the average is O(1) - Expecting
Vec::with_capacity(10)to hold ten elements, so thatv[0]would not panic - Expecting
clearortruncateto return memory, which takesshrink_to_fitorshrink_to
- Why does doubling give amortized O(1), while a fixed growth step gives O(n²) in total?
- When is
reserve_exactbetter thanreserve, and why can it hurt inside a loop?
The program below prints each new capacity of a Vec<i32> and shows that after with_capacity the buffer does not move:
fn main() {
let mut v: Vec<i32> = Vec::new();
let mut caps = vec![v.capacity()];
for i in 0..20 {
v.push(i);
if v.capacity() != *caps.last().unwrap() {
caps.push(v.capacity());
}
}
println!("{caps:?}"); // [0, 4, 8, 16, 32]
let mut w: Vec<i32> = Vec::with_capacity(1000);
let start = w.as_ptr(); // address of the heap buffer
for i in 0..1000 {
w.push(i);
}
println!("{} {}", w.capacity(), start == w.as_ptr()); // 1000 true
w.truncate(10);
println!("{} {}", w.len(), w.capacity()); // 10 1000 — the memory was not returned
w.shrink_to_fit();
println!("{}", w.capacity()); // 10
}A reallocation copies every element, so a single push into a full vector costs O(n). With doubling, though, such pushes become rarer and rarer: adding n elements copies fewer than 2n in total, so on average push costs O(1). Growing by a fixed step would give O(n²). The sequence 0, 4, 8, 16, 32 is an observation for rustc 1.99, not a contract: the documentation promises only amortized O(1).
Vec::with_capacity(n) and reserve(k) pay off when the final size is known up front — for instance, when moving data from one collection to another on a hot path: no reallocation and no extra copy at all. truncate and clear shrink only the length; shrink_to_fit can hand the memory back to the allocator — useful for a long-lived vector that once grew large.