For a Rust `Vec<T>`, how do `len` and `capacity` differ, and when do `with_capacity`, `reserve` and `shrink_to_fit` pay off?
answer
- allocated slots vs used slots
- push reallocates only when full
- never shrinks on its own
- the buffer can move
basics
~20 slen counts the elements a Vec holds; capacity counts the slots its buffer has room for. A push reallocates, possibly moving the buffer, only when len equals capacity, and a Vec never shrinks on its own: shrink_to_fit or shrink_to returns the memory.
solid answer
~40 s`len` is how many elements are initialised; `capacity` is how many fit in the current heap buffer. The docs guarantee `push` never reallocates while capacity is sufficient and *will* reallocate when `len == capacity`; the current implementation at least doubles the capacity, but no growth factor is promised. `Vec::with_capacity(n)` and `reserve(n)` buy one up-front allocation before a known batch, and `reserve_exact` skips the speculative extra room. `clear` and `truncate` keep the capacity, because a `Vec` never shrinks on its own, so a buffer that peaked at a million samples keeps that memory until `shrink_to_fit` or `shrink_to`. Reallocation may move the elements to a new address, which is why the borrow checker rejects a `push` while a reference into the vector is still used (E0502).
code
rust · 21 linesfn main() {
let mut samples: Vec<f64> = Vec::with_capacity(4);
let before = samples.as_ptr();
for i in 0..4 {
samples.push(i as f64); // len reaches capacity: no reallocation yet
}
println!("len {} cap {} moved? {}", samples.len(), samples.capacity(), samples.as_ptr() != before);
samples.push(4.0); // len == capacity, so this push must reallocate
println!("len {} cap >= 5? {}", samples.len(), samples.capacity() >= 5);
samples.reserve(1_000); // one reallocation up front for the next batch
let cap = samples.capacity();
samples.extend((0..1_000).map(|i| i as f64));
println!("cap unchanged by extend? {}", samples.capacity() == cap);
samples.clear(); // len 0, capacity kept: Vec never shrinks on its own
println!("after clear: len {} cap {}", samples.len(), samples.capacity() == cap);
samples.shrink_to_fit();
println!("after shrink_to_fit: cap {}", samples.capacity());
}go deeper
Define len as elements held and capacity as slots allocated, and say that a push beyond capacity allocates a bigger buffer.
Explain the documented rules: push reallocates exactly when len equals capacity, no growth factor is promised, and clear keeps the memory until shrink_to_fit or shrink_to.
Show production habits: reserve before batches, try_reserve for sizes from untrusted input, shrinking long-lived buffers after spikes, and keeping indices rather than references across growth.
Weigh reuse against footprint: retained capacity avoids allocator churn on a steady workload but pins peak memory, so set a floor policy for long-lived buffers.
## Two numbers, one buffer A `Vec<T>` is a header of three words, a pointer, a **capacity** and a **length**, plus a heap buffer it owns. - **`len()`**: how many elements are initialised and visible. - **`capacity()`**: how many elements the current buffer can hold before it must grow. `capacity() >= len()` always holds. The slots between them are uninitialised scratch space that the vector may use as it likes; the docs warn not to rely on removed data being erased. ## When a push reallocates The standard library documents this precisely: `push` and `insert` **never** reallocate when the reported capacity is sufficient, and they **will** reallocate when `len == capacity`. Bulk methods such as `extend` may reallocate even when not strictly necessary. Reallocating means asking the allocator for a bigger block, moving the elements into it and freeing the old one, so **the buffer's address can change**. The growth policy is not part of the contract: the docs promise only amortised O(1) `push`. In rustc 1.99.1 the internal `RawVec` grows to `max(2 * capacity, required)`, so pushing three elements into `Vec::with_capacity(2)` reports capacity 4, but code must not depend on that factor. ## Pre-allocating | Call | What it guarantees | Use it when | |---|---|---| | `Vec::with_capacity(n)` | capacity at least `n`; requests exactly `n` slots from the allocator | the final size is known before the first push | | `reserve(additional)` | capacity at least `len + additional`; may over-allocate | a batch of known size is about to be appended | | `reserve_exact(additional)` | same bound, no deliberate over-allocation | the vector will not grow further | | `try_reserve(additional)` | returns `Err(TryReserveError)` instead of aborting on failure | the size comes from untrusted input | All of them do nothing when the capacity is already sufficient, and `reserve` and `reserve_exact` panic if the new capacity would exceed `isize::MAX` bytes. `Vec::new()` does not allocate at all until elements are pushed. In a time-series buffer that receives 1,000 samples per tick, calling `samples.reserve(1_000)` before the batch turns several reallocations and copies into at most one. ## Memory that does not come back The docs state that `Vec` **never automatically shrinks**, even when completely empty, so that emptying and refilling to the same length makes no allocator calls. The consequences: 1. `clear()` and `truncate(k)` drop elements but leave the capacity untouched. 2. A buffer that peaked at one million samples and now holds twelve still owns room for a million. 3. To return memory, call `shrink_to_fit()` or `shrink_to(min)`; these ask the allocator to shrink, which may reallocate, and the result can still carry some excess. 4. `into_boxed_slice()` discards excess capacity the same way before producing a `Box<[T]>`; when to store that type is covered with `Box`. Shrinking after every compaction would undo the benefit of reuse, so shrink only after a lasting drop in size, for example after a burst ends. ## Why a live reference blocks a push Because a `push` may move the buffer, a `&T` into the old buffer would dangle after it. Rust does not check capacity at run time to decide; `push` takes `&mut self`, and the borrow checker refuses it while a shared borrow of the vector is still used later: ```rust let first = &samples[0]; samples.push(3.0); // error[E0502]: cannot borrow `samples` as mutable println!("{first}"); ``` The rule holds even when spare capacity means this particular push would not move anything; the lesson on the borrow checker covers the fixes, such as keeping an index or copying the value out first. ## A worked example: the sample buffer A monitoring agent keeps the last few minutes of readings in a `Vec<f64>`. Each tick it calls `reserve(batch.len())`, appends the batch with `extend`, and every minute it compacts the buffer. In a steady state the capacity settles at the peak working size and the allocator is never called again, which is exactly the reuse the never-shrink rule is designed for. After a one-off burst ten times the usual rate, the buffer would hold ten times the memory forever; a `shrink_to(normal_peak)` after compaction returns the excess while keeping room for normal traffic. ## Checklist - Know the size up front: `with_capacity`. - Appending a known batch: `reserve`. - Size from an attacker or a file header: `try_reserve`, and handle the error. - Long-lived buffer after a spike: `shrink_to` a sensible floor rather than `shrink_to_fit` to zero. - Never hold a reference across a `push`; hold an index.
- In Rust, does `Vec::push` cost O(1) every time?No. The documented guarantee is amortised O(1): most pushes write into spare capacity, but a push at `len == capacity` reallocates and moves every element, which costs O(n) for that call. Latency-sensitive code calls `with_capacity` or `reserve` up front so the expensive push does not land in a hot path.
- When the element count comes from an untrusted file header, how should a Rust `Vec` be pre-allocated?Call `try_reserve(n)` and handle the `Err(TryReserveError)`, or cap `n` before calling `with_capacity`. `with_capacity` and `reserve` panic on capacity overflow, and an allocation failure aborts the process by default, so a hostile header claiming billions of elements must not reach them unchecked.
- clear() frees the vector's heap buffer
- Vec always doubles its capacity, and code can rely on that
- push never reallocates if you called reserve once at startup
- Rust allows holding &v[0] across a push when capacity has room
- shrink_to_fit guarantees capacity equals len afterwards