Sub topic 8
Length, capacity and reallocation
This chapter assumes you can create a Vec, push to it, and read it with indexing or get. It also assumes you know what a move and a borrow are. Here you will see how a Vec manages its memory, and how to avoid needless reallocation.
Length versus capacity
A Vec<T> tracks two numbers.
- Length (
len) is the number of elements currently stored. - Capacity (
capacity) is the number of elements the Vec can hold in its current heap buffer before it must get a bigger one.
Capacity is always at least the length. The slots between the two exist but hold no values yet.
A Vec itself is a small value with three fields: a pointer to the heap buffer, the length, and the capacity. The elements live in the buffer.
What happens on push
When you push and len == capacity, the Vec has no room. It allocates a larger buffer, moves the existing elements into it, and frees the old buffer. This is a reallocation. It costs time proportional to the current length, and it moves the elements to a new address.
The standard library grows the buffer geometrically, so the cost of reallocation averages out. Pushing is amortized constant time. The exact growth factor is an implementation detail, so do not depend on specific capacity numbers.
Watching capacity change
You can observe growth by printing the capacity each time it changes.
fn main() {
let mut v: Vec<u32> = Vec::new();
println!("start: len = {}, cap = {}", v.len(), v.capacity());
let mut last_cap = v.capacity();
for i in 0..20 {
v.push(i);
if v.capacity() != last_cap {
last_cap = v.capacity();
println!("len = {}, cap = {}", v.len(), v.capacity());
}
}
}A new Vec has capacity 0 and allocates nothing. The capacity then jumps at certain pushes. The exact values may differ between Rust versions.
Reserving space with with_capacity
If you know roughly how many elements you will add, reserve the space once.
fn main() {
let mut v: Vec<u32> = Vec::with_capacity(10);
assert!(v.capacity() >= 10);
assert_eq!(v.len(), 0);
for i in 0..10 {
v.push(i);
}
// No reallocation happened: capacity was reserved up front.
println!("len = {}", v.len()); // len = 10
}with_capacity(10) creates an empty Vec. Its length is 0, not 10. The capacity is at least 10, so assert with >= and never with ==.
Two related methods help when the Vec already exists:
reserve(n)makes sure there is room fornmore elements beyond the current length.shrink_to_fit()asks the Vec to release unused capacity. It is a request, and the allocator may keep some extra space.
Reallocation and references
A reallocation moves the elements, so any reference into the old buffer would dangle. This is why the borrow checker rejects a push while you hold a reference into the Vec. Pushing might reallocate. Reserving capacity does not remove that rule. The compiler does not track capacity, so it still rejects the push.
When it matters
| Situation | Advice |
|---|---|
| Final size known or estimated | Use `with_capacity` or `reserve` |
| Small Vec, size unknown | Use `Vec::new` and let it grow |
| Vec built once, then kept long-term | Consider `shrink_to_fit` |
| Clearing and refilling in a loop | Use `clear()`, which keeps the capacity |
Treat with_capacity as an optimization. It does not change what the program means, only how often it allocates. Measure before tuning anything that is not obviously a hot loop.
Exercise
You run let mut v = Vec::with_capacity(4); v.push(1); v.push(2);. What are v.len() and v.capacity(), and does v[3] compile and run safely?
Show answer
The length is 2 and the capacity is at least 4. v[3] compiles, but it panics at run time because index 3 is not below the length. Capacity only reserves space and does not create elements.
Exercise
Why can v.push(x) reallocate, and how does that explain the compiler error when you hold let first = &v[0]; across the push?
Show answer
When length equals capacity, push allocates a bigger buffer and moves the elements. first points into the old buffer, so after a reallocation it would dangle. The borrow checker prevents this by refusing the push while the shared reference is still in use.