Sub topic 6
Preallocating with with_capacity and reserve
This chapter assumes you know how Vec and String own heap memory, and that you can run cargo run and read the output of a small benchmark. You should also have seen the counting allocator from the measurement chapter. Here you will learn how a growable collection chooses its size, how to tell it the size up front, and when doing so is a mistake.
Length, capacity and growth
A Vec<T> stores three values: a pointer to a heap buffer, a length, and a capacity. The length is the number of initialized elements. The capacity is the number of elements the buffer can hold before it must grow.
push checks whether len == capacity. If so, the vector asks the allocator for a bigger buffer, copies the elements across (or extends the block in place when the allocator can), and frees the old one. This is a reallocation. String, VecDeque, HashMap and HashSet follow the same idea with their own details.
The standard library grows capacity geometrically, so appending n items costs amortized O(1) per item. The exact policy is an implementation detail. On current stable compilers, an empty Vec starts with no allocation. The first push allocates room for 4 elements (8 for one-byte elements, 1 for elements larger than 1 KiB). Capacity then doubles.
Pushing 1000 u32 values one by one therefore walks through capacities 4, 8, 16, 32, 64, 128, 256, 512 and 1024. That is nine allocator calls, and about 2 KiB of data gets copied along the way. It also leaves 24 slots unused at the end.
Measuring the difference
Do not assume the saving. Count it. This program wraps the system allocator and counts both alloc and realloc. It then runs the two builders from the earlier chapters.
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { System.dealloc(ptr, layout) }
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { System.realloc(ptr, layout, new_size) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
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
}
fn count<T>(f: impl FnOnce() -> T) -> (T, usize) {
let before = ALLOCS.load(Ordering::Relaxed);
let value = f();
let after = ALLOCS.load(Ordering::Relaxed);
(value, after - before)
}
fn main() {
let (a, a_calls) = count(|| grow_without_hint(1000));
let (b, b_calls) = count(|| grow_with_capacity(1000));
println!("no hint: len {}, capacity {}, allocator calls {}", a.len(), a.capacity(), a_calls);
println!("with_capacity: len {}, capacity {}, allocator calls {}", b.len(), b.capacity(), b_calls);
}On a current stable toolchain this prints 9 allocator calls and capacity 1024 for the first vector. It prints 1 call and capacity 1000 for the second. Your numbers may differ slightly, because the growth policy is not guaranteed. The ratio is what matters.
with_capacity: when you know or can estimate the size
Vec::with_capacity(n) allocates room for n elements and leaves the length at 0. The same constructor exists on String, VecDeque, HashMap, HashSet, BinaryHeap and PathBuf.
Use it when one of these holds:
- You know the exact final size, for example when you transform a slice element by element.
- You can compute a cheap upper bound, such as the sum of the input lengths.
- You can make a good estimate, such as a typical line length times the number of lines.
Here the bound comes from the data type itself. A u32 has at most 10 decimal digits, and each item needs one separator.
use std::fmt::Write;
fn join_ids(ids: &[u32]) -> String {
let mut out = String::with_capacity(ids.len() * 11);
for (i, id) in ids.iter().enumerate() {
if i > 0 {
out.push(',');
}
write!(out, "{}", id).unwrap();
}
out
}
fn main() {
println!("{}", join_ids(&[7, 42, 4_000_000_000]));
}The estimate does not need to be exact. An estimate that is too small still works, because the vector grows normally once it runs out. An estimate that is too large wastes memory but never breaks the program.
Capacity is not length
A common mistake is to treat with_capacity as if it created elements.
fn main() {
let mut v: Vec<u8> = Vec::with_capacity(16);
println!("len {}, capacity {}", v.len(), v.capacity());
// v[0] = 1; // would panic: index out of bounds, len is 0
v.push(1);
println!("len {}, capacity {}", v.len(), v.capacity());
}Indexing past len panics even though the memory is reserved. If you need 16 zeroed elements, use vec![0u8; 16] or resize. capacity() also returns at least the requested value, and it may return more. Do not assert that it equals what you asked for.
reserve: when the vector already exists
Sometimes the collection is passed in, or you learn the size only after you start. reserve(additional) ensures that capacity >= len + additional. It does nothing if there is already enough room.
fn append_all(dst: &mut Vec<u32>, chunks: &[Vec<u32>]) {
let extra: usize = chunks.iter().map(|c| c.len()).sum();
dst.reserve(extra);
for chunk in chunks {
dst.extend_from_slice(chunk);
}
}
fn main() {
let mut all = vec![1, 2, 3];
append_all(&mut all, &[vec![4, 5], vec![6], vec![7, 8, 9]]);
println!("{:?}", all);
}The argument is the number of additional elements, not the target capacity. v.reserve(100) on a vector with length 50 aims for capacity 150 or more.
reserve versus reserve_exact
| Method | Behavior | Use when |
|---|---|---|
| `reserve(n)` | May allocate more than needed, so later growth stays amortized | You will keep appending after this call |
| `reserve_exact(n)` | Asks for exactly `len + n`, though the allocator may still round up | The collection is finished growing after this call |
| `shrink_to_fit()` | Releases spare capacity, possibly reallocating | A long-lived collection is done growing and its slack matters |
Calling reserve_exact repeatedly in a loop is a trap. Each call can reallocate by a small step, which turns amortized O(1) appends into O(n²) total copying. Reserve for the whole batch once, or use plain reserve.
Collecting and extending already use size hints
Many cases need no manual call. collect::<Vec<_>>() and extend read the iterator's size_hint and reserve accordingly. For ranges, slices, map over those, and Vec iterators, the hint is exact, so this performs one allocation:
fn squares(n: u32) -> Vec<u64> {
(0..n).map(|i| u64::from(i) * u64::from(i)).collect()
}
fn main() {
let v = squares(5);
println!("{:?} capacity >= {}", v, v.len());
}A filter in the chain makes the lower bound 0, so the collector starts small and grows. If you know the filter keeps most items, you can build with Vec::with_capacity and extend instead. Do this only if a measurement shows reallocation matters.
Guarding against hostile sizes
with_capacity(n) and reserve abort the process (or panic on capacity overflow) if the allocation fails. When n comes from a network header or a file, an attacker can pick a huge value. Check the value against a limit, and use the fallible versions, try_reserve and try_reserve_exact.
use std::collections::TryReserveError;
const MAX_PAYLOAD: usize = 16 * 1024 * 1024;
fn alloc_payload(len: usize) -> Result<Vec<u8>, TryReserveError> {
let len = len.min(MAX_PAYLOAD);
let mut buf = Vec::new();
buf.try_reserve_exact(len)?;
buf.resize(len, 0);
Ok(buf)
}
fn main() {
match alloc_payload(1024) {
Ok(buf) => println!("got {} bytes", buf.len()),
Err(e) => println!("allocation failed: {e}"),
}
}Silently clamping the length, as above, is only appropriate if the caller handles a shorter buffer. In a real protocol, reject oversized lengths with an error instead.
Choosing when to preallocate
Preallocation is most useful for large collections, for code in hot loops that builds a fresh collection on every call, and for code that appends in several steps. It helps little when:
- The collection holds a handful of items. The savings are a few allocator calls, and
SmallVec(a later chapter) may serve better. - Your estimate is wildly high. A
with_capacity(1_000_000)for a typical result of 10 items costs memory, and large allocations may also touch more pages than needed. - The collection is built once at startup. The cost is paid once and does not matter.
Also keep an eye on retained memory. A Vec that grew to hold a rare large input keeps that capacity until you drop it or call shrink_to_fit. For a long-lived buffer in a server, that is sometimes what you want, and the next chapter on buffer reuse builds on it.
Summary
- Capacity is the allocated room, length is the number of items, and growth is geometric but not guaranteed to follow any exact policy.
- Use
with_capacityat construction when you can bound the size, andreserveonce before a batch when the collection already exists. - Prefer
reserveoverreserve_exactunless the collection is finished growing, and never call either per element. - Validate sizes from untrusted input and use
try_reservefor them. - Count allocator calls before and after the change.
Exercise
A function receives words: &[&str] and returns them joined with a single space as a String, built with String::new() and repeated push_str. Write the capacity expression you would pass to String::with_capacity so that, for ASCII input, the buffer never needs to grow. Does the answer change if you instead use reserve_exact once the vector exists?
Show answer
Capacity is the sum of the word lengths plus one separator between each pair: words.iter().map(|w| w.len()).sum::<usize>() + words.len().saturating_sub(1). len() counts bytes, so this is exact for any UTF-8 input, not only ASCII. With an existing String, out.reserve_exact(that_value) gives the same result when the string is empty and finished growing after this call. If you would keep appending later, use reserve so that growth stays amortized.
Exercise
You run the counting allocator on a function that builds a Vec<String> of 500 items using Vec::with_capacity(500), yet it still reports about 501 allocations. Why, and does with_capacity have a bug?
Show answer
There is no bug. with_capacity(500) removes only the allocations for the outer vector's buffer (one instead of about eight). Each String element owns its own heap buffer, so 500 strings still account for roughly 500 allocations. To reduce those, you would borrow with &str, reserve capacity per string, or use a different representation, which later chapters cover.