Rust Reference ยท Collections
Rust Vec capacity and reserve
Reference for Vec::capacity, with_capacity, reserve, reserve_exact, shrink_to_fit and try_reserve in Rust: how growth works and when to preallocate.
A vector's length is how many elements it holds; its capacity is how many it can hold before it has to allocate a bigger buffer. The methods on this page let you inspect and steer that: capacity() reads it, with_capacity and reserve raise it ahead of time, and shrink_to_fit gives memory back.
Capacity is a performance tool, never a correctness one. A vector with spare capacity behaves exactly like one without; it just avoids copying its elements to a new buffer on growth.
let mut v: Vec<u32> = Vec::with_capacity(1000); assert!(v.capacity() >= 1000 && v.is_empty());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> Vec<T> { pub fn capacity(&self) -> usize; pub fn with_capacity(capacity: usize) -> Vec<T>; pub fn reserve(&mut self, additional: usize); pub fn reserve_exact(&mut self, additional: usize); pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>; pub fn shrink_to_fit(&mut self); pub fn shrink_to(&mut self, min_capacity: usize); }
| Name | Description |
|---|---|
additional |
How many more elements, beyond the current len, the vector should be able to hold without reallocating. |
min_capacity |
For shrink_to, a lower bound the capacity will not go below. |
Returns: capacity returns a usize. try_reserve returns Err(TryReserveError) on capacity overflow or when the allocator refuses.
Panics and aborts: reserve panics on capacity overflow and aborts the process if the allocator fails. Use try_reserve for untrusted sizes.
Usage notes
- After
reserve(n)the capacity is at leastlen + n, often more because the allocator may round up.reserve_exactasks for no extra slack, but still does not promise an exact number. - Growth is geometric. When a push finds the buffer full, the new capacity is at least double (with a small minimum). The exact sequence is not part of the contract, so never print or rely on it.
- Preallocate when you know the size.
Vec::with_capacity(n)before a loop ofnpushes, orcollect()from an iterator with a good size hint, avoids repeated copies. - Capacity is not length. Indexing past
lenpanics even if capacity is large; the spare slots are uninitialized memory. clear,truncateandpopkeep the buffer. Useshrink_to_fitafter a big vector becomes small and long-lived. It may reallocate, so do not call it in a hot loop.clone()does not copy capacity; the clone is sized to the length (not guaranteed, but typical).- Moving a
Vecis cheap (three words) regardless of capacity; the buffer stays where it is. - Memory use is roughly
capacity * size_of::<T>()plus the 24-byte header on a 64-bit target.
Related
Vec<T>,Vec::new, push, pop,String,std::alloc- Lessons: Vectors, Performance