Sub topic 9
Small-buffer collections such as SmallVec
This chapter assumes you know how Vec grows, what with_capacity does, and how to measure allocations with a counting allocator. Those topics come from earlier chapters.
The problem: many tiny vectors
A Vec<T> always keeps its elements on the heap. Even a vector holding two items costs one allocation, plus a reallocation each time it outgrows its capacity. This adds up when a program creates millions of short vectors, for example the children of each node in a tree or the tokens on each line of a log file.
A small-buffer collection avoids this. It reserves space for a few elements inside the value itself. The elements stay there until you add more than fit. Then the collection moves them to the heap and behaves like a Vec.
Using SmallVec
SmallVec comes from the smallvec crate. Add it with cargo add smallvec. The type parameter is an array type that sets the inline capacity: SmallVec<[u32; 8]> holds up to eight u32 values inline.
use smallvec::{smallvec, SmallVec};
fn main() {
let mut v: SmallVec<[u32; 8]> = smallvec![1, 2, 3];
v.push(4);
println!("{:?}, spilled to heap: {}", v, v.spilled());
for i in 5..20 {
v.push(i);
}
println!("len = {}, spilled to heap: {}", v.len(), v.spilled());
}The first line prints spilled to heap: false, because four elements fit in eight slots. The second prints true. Pushing the ninth element triggers the move to the heap. spilled() reports which state the vector is in.
SmallVec dereferences to a slice, so iter(), indexing, sort(), and len() work as they do on Vec. Call into_vec() when an API needs a real Vec. That call allocates if the data is still inline.
What it costs
Inline storage is not free:
- Larger values. A
SmallVec<[u64; 8]>is at least 64 bytes of elements plus a length field. AVecis 24 bytes. Moving or returning a largeSmallVeccopies all of it. - An extra branch. Each access checks whether the data is inline or on the heap.
- No automatic return to inline. After a spill, the data stays on the heap even if you remove elements.
shrink_to_fit()can move it back inline.
The choice of N matters most. If N is too small, most vectors spill and you pay for both the inline space and the allocation. If N is too large, you waste memory and slow down moves.
When to use it
| Situation | Better choice |
|---|---|
| Many vectors, most with 0 to 8 elements | `SmallVec` |
| One long-lived vector, or a few large ones | `Vec` |
| Length is known up front and large | `Vec::with_capacity` |
| Hard upper bound, never more than N items | A fixed-capacity type such as `ArrayVec` from the `arrayvec` crate |
| Vectors are moved or returned very often and `N` is large | `Vec` |
Only replace Vec where a measurement shows allocation cost. Change one type, run your benchmark, and keep the change only if the numbers improve. A single Vec on a cold path gains nothing from SmallVec.
Exercise
A parser builds a SmallVec<[Token; 16]> for each line. Profiling shows that 40% of lines have more than 16 tokens, and size_of::<Token>() is 32 bytes. Is this a good use of SmallVec? What would you check or change?
Show answer
It is probably a poor fit. With 40% of lines spilling, those lines pay for 512 bytes of unused inline space and a heap allocation. Every line also moves a value of more than 512 bytes. Check the distribution of line lengths and try a larger N only if the larger inline size is acceptable. Otherwise use Vec with a reused buffer, clearing it between lines, which removes most allocations without the size cost. Compare allocation counts and timings for each option.