Sub topic 6
Preallocating with with_capacity and reserve
This chapter assumes you know Rust ownership and borrowing, can use Vec and String, and can run cargo test. It also assumes you have seen how a counting allocator works from the earlier chapter on measuring allocations.
Why growth costs allocations
A Vec has a length (how many elements it holds) and a capacity (how many it can hold before it must get more memory). When push finds the vector full, it allocates a larger block, copies the elements over, and frees the old block. The capacity grows geometrically, so pushes are cheap on average. The reallocations still cost time, and each one can move all the existing data.
If you know the final size up front, you can ask for it once.
fn grow_without_hint(n: u32) -> Vec<u32> {
let mut v = Vec::new();
for i in 0..n {
v.push(i);
}
v
}
fn grow_with_capacity(n: u32) -> Vec<u32> {
let mut v = Vec::with_capacity(n as usize);
for i in 0..n {
v.push(i);
}
v
}The first function may reallocate several times as the vector grows. The second allocates once, because the final length is known.
with_capacity
Vec::with_capacity(n) and String::with_capacity(n) allocate room for at least n elements and leave the length at 0. The same constructor exists on VecDeque, HashMap, HashSet, BinaryHeap and others.
fn main() {
let v: Vec<u32> = Vec::with_capacity(100);
println!("len = {}, capacity >= 100: {}", v.len(), v.capacity() >= 100);
}Capacity is a lower bound. The standard library may give you more, so compare with >= and never assert an exact value.
reserve when the size shows up later
Sometimes you only learn the size after a container exists. reserve(additional) makes sure there is room for additional more elements beyond the current length.
fn append_all(dst: &mut Vec<u32>, src: &[u32]) {
dst.reserve(src.len());
dst.extend_from_slice(src);
}
fn main() {
let mut data = vec![1, 2, 3];
append_all(&mut data, &[4, 5, 6]);
println!("{:?}", data);
}reserve may over-allocate to keep growth geometric. If you are sure no more elements will come, reserve_exact asks for exactly the amount, but the allocator can still return more.
Using size hints from iterators
You often get a good estimate for free. collect already uses the iterator's size_hint, so collecting from map over a slice allocates once. When you push in a loop by hand, call with_capacity with the input length.
fn lengths(words: &[&str]) -> Vec<usize> {
let mut out = Vec::with_capacity(words.len());
for w in words {
out.push(w.len());
}
out
}
fn main() {
println!("{:?}", lengths(&["a", "bcd", "ef"]));
}Check the effect
Use the counting allocator from the measuring chapter to confirm the saving rather than assuming it. Run each function inside a before/after count. The hinted version should report one allocation for a non-empty result, and the unhinted version should report several for large n.
Pitfalls
- Over-reserving.
with_capacity(1_000_000)for a vector that holds ten items wastes memory. Use an estimate you trust. - Untrusted sizes. Do not pass a length read from input straight to
with_capacity. A hostile value can exhaust memory. Cap it, or usetry_reserve, which returns an error instead of aborting. - Capacity is not length. A vector from
with_capacity(10)has no elements. Indexingv[0]panics. - Leftover space. After building,
shrink_to_fitcan release unused capacity, but it may reallocate, so use it only for long-lived data.
Exercise
You are writing a function that takes ids: &[u64] and returns a Vec<String> with one formatted string per id, built with a for loop and push. What single line should you add before the loop to avoid reallocation of the outer vector, and does it remove the allocation for each string?
Show answer
Add let mut out = Vec::with_capacity(ids.len()); and push into out. This makes the outer vector allocate once. It does not remove the per-item allocations, because each String still allocates its own buffer.