Sub topic 9
Small-buffer collections such as SmallVec
This chapter assumes you know how Vec grows and when it allocates. It also assumes you can measure allocation counts, as covered earlier in this tutorial. You should be comfortable with generics, const-sized arrays, and adding a crate to Cargo.toml.
The problem: many collections that are almost always tiny
A Vec<T> stores its elements on the heap. Pushing the first element allocates, and growing past capacity reallocates. That cost is fine for one large buffer. It hurts when a program creates millions of tiny collections, such as:
- the segments of a URL path (usually 2 to 6),
- the arguments of a function call node in a parser (usually 0 to 3),
- the tags on a record (usually 0 to 4).
Each of these costs one allocation and one free, even though the data would fit in a few dozen bytes. A small-buffer collection stores up to N elements inside the value itself. Only when the length exceeds N does it move the elements to the heap.
How SmallVec works
SmallVec<[T; N]> from the smallvec crate has the same shape of API as Vec<T>. The type parameter is an array type, not a number. Internally it holds one of two states:
- Inline: elements live in a
[T; N]buffer inside the struct. No heap memory is used. - Spilled: elements live in a heap buffer, as in a
Vec.
Add the crate:
[dependencies]
smallvec = "1"The example below is the same one used in the tutorial's code samples:
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());
}This prints [1, 2, 3, 4], spilled to heap: false. Four u32 values fit in the inline buffer of eight, so the program makes no heap allocation for the vector. spilled() reports whether the data has moved to the heap.
A realistic example
Splitting a path into segments is a typical case. The result is usually short, but you cannot put a hard upper bound on it.
use smallvec::SmallVec;
fn segments(path: &str) -> SmallVec<[&str; 8]> {
path.split('/').filter(|s| !s.is_empty()).collect()
}
fn main() {
let short = segments("/usr/local/bin");
let long = segments("/a/b/c/d/e/f/g/h/i/j");
println!("{:?} spilled: {}", short, short.spilled());
println!("{:?} spilled: {}", long, long.spilled());
}The output is:
["usr", "local", "bin"] spilled: false
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] spilled: trueThree details matter here:
- The function returns the collection by value. That is safe because a
SmallVecowns its inline buffer. The&stritems borrow frompath, so no strings are copied either. - The long path still works. It spills, pays one allocation, and behaves like a
Vecfrom then on. - Callers use it through
Deref<Target = [T]>, so indexing, iteration,len,firstand slice methods work as they do on aVec.
The costs you accept
A small-buffer type trades allocation count for other costs. Check these before adopting it.
Larger values and more copying
A Vec<T> is three words (pointer, capacity, length), 24 bytes on a 64-bit target. A SmallVec<[u32; 8]> has to hold 32 bytes of inline storage plus length information, so it is noticeably larger. Moving it (returning it, pushing it into another collection, passing it by value) copies all of those bytes, even when only two elements are in use.
You can see the difference directly:
use smallvec::SmallVec;
use std::mem::size_of;
fn main() {
println!("Vec<u32>: {} bytes", size_of::<Vec<u32>>());
println!("SmallVec<[u32; 8]>: {} bytes", size_of::<SmallVec<[u32; 8]>>());
println!("SmallVec<[u32; 64]>: {} bytes", size_of::<SmallVec<[u32; 64]>>());
}The exact numbers depend on the crate version and enabled features, so measure on your own build. The pattern is stable: size grows linearly with N.
A branch on every access
Each access has to check whether the data is inline or on the heap. The branch is cheap and well predicted, but it is not free. For a hot loop over a large collection, a plain Vec can be faster.
Spilling is a one-way trip
After a spill the data stays on the heap, even if you later remove elements. shrink_to_fit() can move it back inline when it fits. Otherwise, clearing a spilled SmallVec keeps its heap buffer, which is the same behavior as Vec::clear.
Pitfalls with stack use
Inline storage lives wherever the owning value lives. A SmallVec<[u8; 4096]> as a local variable puts 4 KiB on the stack. Inside a recursive function, or in a type that is itself stored in a large array, this can overflow the stack or bloat memory use.
Choosing N
Pick N so that most real inputs stay inline, without wasting space on the rest.
- Record the length distribution of the collection in a realistic workload. A histogram or a simple counter is enough.
- Choose
Nnear a high percentile, such as the 90th or 95th, as long asN * size_of::<T>()stays small (tens of bytes, not kilobytes). - Re-measure allocation counts and wall-clock time. Keep the change only if both improve or the allocation reduction clearly matters for your workload.
If 99% of your collections have 0 or 1 elements, N = 1 or N = 2 may beat N = 8. A smaller value is cheaper to move.
Alternatives and when to use them
| Type | Where elements live | If you exceed capacity | Use when |
|---|---|---|---|
| `Vec<T>` | Heap | Reallocates | Lengths are unknown or large. Simplest option. |
| `SmallVec<[T; N]>` | Inline up to `N`, then heap | Spills to heap | Most collections are short, but long ones must still work. |
| `ArrayVec<T, N>` (`arrayvec` crate) | Always inline | Returns an error or panics, depending on method | You have a true upper bound and want no heap at all. |
| `[T; N]` | Inline | Not applicable | The length is fixed and known at compile time. |
ArrayVec is the right tool only when exceeding N is a bug or can be reported as an error. If a long input is valid and must work, use SmallVec.
Combining with other techniques
Small-buffer collections work well with the techniques from nearby chapters:
- With borrowing:
SmallVec<[&str; 8]>, as above, avoids both the vector allocation and the string copies. - With iterators: collecting into a
SmallVecis a cheap way to materialize a short result when you do need a collection. If you only consume the items once, a lazy iterator chain avoids the collection entirely. - With buffer reuse: reusing a
Vecacross loop iterations removes allocations after the first. ASmallVecalso helps when each iteration needs its own independent collection that you cannot reuse, for example because each one is stored in a result.
Verifying the change
Treat the swap as an experiment:
- Count allocations before the change, using the counting allocator from the measurement chapter.
- Replace
Vec<T>withSmallVec<[T; N]>at the hot site. Most code compiles unchanged because of the sliceDeref. - Count again. Check allocations per operation, not just a total.
- Run a benchmark. A drop in allocations that is paired with a slower benchmark usually means
Nis too large or the values are being moved too often.
Where Vec<T> appears in a public API, replacing it with SmallVec changes your crate's interface and ties your users to the smallvec crate version. Keep it as an internal detail when you can, and convert at the boundary with into_vec().
Summary of when it helps
- You create a very large number of collections, not one large one.
- Most have a small, bounded typical length.
- The element type is small, so inline storage stays small.
- Measurements show the allocation cost, not just a guess that it exists.
Exercise
A parser builds one Vec<Expr> of arguments per function call node. In a profile, 95% of call nodes have 3 or fewer arguments, but a few have more than 100. Expr is 16 bytes. Would you use SmallVec<[Expr; 4]>, ArrayVec<Expr, 4>, or keep Vec<Expr>? Explain what you would measure to confirm.
Show answer
Use SmallVec<[Expr; 4]>. Inline storage is 64 bytes, which is small, and the common case of 3 or fewer arguments stays inline with no allocation. ArrayVec<Expr, 4> is wrong because calls with more than 4 arguments are valid and must work, and ArrayVec cannot grow past 4. Keeping Vec is reasonable if call nodes are not a measured hotspot. To confirm, count allocations before and after with a counting allocator on a realistic input, and run a benchmark to check that the larger node size and extra branch do not make parsing slower overall.
Exercise
You change a field from Vec<u8> to SmallVec<[u8; 1024]> in a struct that is created 10 million times, and allocations drop to near zero but the program gets slower and uses more memory. What are two likely causes, and what do you do?
Show answer
Each struct now carries at least 1024 bytes of inline storage even when the data is empty or tiny, so memory use rises and cache behavior worsens. Moving or copying the struct also copies that whole buffer. Reduce N to a value that covers most real lengths (found from a length histogram), or go back to Vec and reuse buffers if the structs are not all alive at once. Re-measure both allocation counts and run time after the change.