Sub topic 1
Where allocations come from: stack, heap and the allocator
Every Rust value lives somewhere in memory. Often the choice of place costs nothing. Sometimes it costs a call into the allocator, a library routine that finds free memory, and that call is the cost this tutorial teaches you to remove. This chapter builds the model you need: where values live, which types ask the allocator for memory, and what an allocation costs.
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing and lifetimes in Rust.
- Basic use of
Vec,StringandBox. - How to read iterator and closure code.
- How to run
cargo build,cargo testandcargo bench.
You do not need to know anything about allocators or profilers. Later chapters cover measurement and the individual techniques.
Two places for data: stack and heap
The stack is a region of memory that each thread uses for function calls. When a function is called, the compiler reserves one block, called a frame, for all of its local variables. The size of the frame is fixed at compile time. Reserving it takes one adjustment of the stack pointer, and leaving the function releases it with another. No search for free space happens.
The heap is a pool of memory that a program requests at run time, in whatever size it needs. The request goes to the allocator, which finds a free block and returns a pointer to it. When the owner of the value is dropped, the block is handed back.
This gives two rules of thumb:
- A value whose size is known at compile time can live on the stack. Examples are integers, tuples, arrays like
[u8; 32], and structs made of them. - A value whose size is only known at run time, or that must grow, needs the heap. Examples are the text in a
Stringand the elements in aVec.
Compared with the stack, a heap allocation costs more in three ways:
- Call cost. The allocator must find a suitable free block, and
deallocmust return it later. Both take far more time than moving a stack pointer. - Contention. Allocators shared by many threads may need internal synchronization. Some do this better than others.
- Locality. Heap blocks may be spread across memory, so the CPU cache serves them less well than the tightly packed stack.
One allocation is cheap in absolute terms. The cost appears when code allocates inside a hot loop, millions of times.
Handle on the stack, data on the heap
Most Rust collection types are split in two. A small fixed-size handle lives wherever you put the variable, usually the stack. It holds a pointer to heap memory, plus a length and a capacity where relevant.
use std::mem::size_of;
fn main() {
println!("u64: {}", size_of::<u64>());
println!("[u8; 32]: {}", size_of::<[u8; 32]>());
println!("&str: {}", size_of::<&str>());
println!("String: {}", size_of::<String>());
println!("Vec<u32>: {}", size_of::<Vec<u32>>());
println!("Box<u64>: {}", size_of::<Box<u64>>());
println!("Option<Box<u64>>: {}", size_of::<Option<Box<u64>>>());
println!("Box<dyn Fn()>: {}", size_of::<Box<dyn Fn()>>());
}On a 64-bit target this prints 8, 32, 16, 24, 24, 8, 8 and 16. Read the numbers like this:
- A
Stringand aVec<u32>are both 24 bytes: pointer, length and capacity, 8 bytes each. The text or the elements sit elsewhere, on the heap. - A
&stris 16 bytes: a pointer and a length. It points at data owned by someone else and owns nothing. - A
Box<u64>is a single pointer.Option<Box<u64>>is the same size becauseNoneuses the null pointer value, which aBoxcan never hold. - A
Box<dyn Fn()>is 16 bytes. It is a "fat pointer": one pointer to the data and one to a table of methods for the concrete type.
This split explains two behaviors that surprise people:
- Moving a
Vecis cheap. A move copies the 24-byte handle. The elements stay where they are. - Cloning a
Vecis not.clonemust allocate a new heap block and copy every element into it.
Which types allocate
You can often tell whether code allocates from the types involved. The table lists common cases.
| Expression | Allocates? | Notes |
|---|---|---|
| `let x = 5u64;` | No | Lives on the stack. |
| `[0u8; 64]` | No | Fixed-size array, stack. |
| `"literal"` (a `&'static str`) | No | The bytes are stored in the program binary. |
| `String::new()`, `Vec::new()` | No | Capacity starts at 0. No heap block exists yet. |
| `Vec::with_capacity(0)` | No | Same as above. |
| `String::from("hi")`, `"hi".to_string()` | Yes | Copies the bytes to the heap. |
| `vec.push(x)` on a full `Vec` | Yes | Grows the buffer, which may also copy the old elements. |
| `v.clone()` where `v: Vec<T>` | Yes | One block, plus more if `T` itself allocates. |
| `format!(...)` | Yes | Creates a new `String` each time. |
| `Box::new(x)` | Yes | Unless `x` is zero-sized. |
| `Rc::new(x)`, `Arc::new(x)` | Yes | One block, holding the value and its reference counts. |
| `HashMap::new()` | No | The table is allocated on first insert. |
Zero-sized types are an edge case. Box::new(()) and Vec<()> never call the allocator, because there are no bytes to store.
A Vec also does not allocate once per element. It grows geometrically, so the number of allocations for n pushes is about log₂(n), not n. The next function shows this.
fn main() {
let mut v: Vec<u32> = Vec::new();
let mut last_cap = v.capacity();
println!("start: capacity {}", last_cap);
for i in 0..100 {
v.push(i);
if v.capacity() != last_cap {
last_cap = v.capacity();
println!("len {:>3}: capacity grew to {}", v.len(), last_cap);
}
}
}With the current standard library this prints capacities 4, 8, 16, 32, 64 and 128. The exact sequence is an implementation detail and may change between releases, but doubling has been the rule. Each growth step asks the allocator to extend the block. If it cannot extend in place, it allocates a larger block, copies the old contents and frees the old block. That is why a later chapter on preallocation matters: if you know the final length, you can skip every one of these steps.
The allocator
Rust does not manage the heap itself. Every heap allocation goes through the global allocator, a single program-wide implementation of the GlobalAlloc trait. By default this is the system allocator: malloc and free from the C library on Linux and macOS, and the Windows heap on Windows.
The trait has two required methods, alloc and dealloc, and each takes a Layout. A Layout holds the size and alignment of the request. Collections such as Vec, String, Box, Rc and HashMap all end up in these two methods. Because every allocation passes through one place, you can wrap that place to count calls, and you can replace it with a different allocator. The next chapter does the first and the last chapter of this tutorial discusses the second.
Allocation does not stop at the allocator. For large requests, the system allocator asks the operating system for pages of memory, and the OS may not back them with physical memory until you touch them. So the cost of a single large allocation includes more than the allocator call itself.
Stack limits and `Box`
The stack is fast but small. The main thread on Linux typically gets 8 MiB. Threads you spawn with std::thread get 2 MiB by default. A very large array in a local variable can overflow it:
fn main() {
// Typically fine: 64 KiB on the stack.
let small = [0u8; 64 * 1024];
println!("{}", small.len());
// Heap-backed alternative for big buffers.
let big = vec![0u8; 64 * 1024 * 1024];
println!("{}", big.len());
}Do not reach for Box::new([0u8; N]) with a large N as the fix. The array may be built on the stack first and then moved to the heap, particularly in debug builds, so the overflow can still happen. A vec![0u8; N] allocates on the heap directly.
The reverse mistake is also common. Boxing a small value to "save stack space" adds an allocation and a pointer hop for no gain. Stack space is rarely the constraint for values of a few dozen bytes.
What this means for reducing allocations
The model gives you a way to read code for allocation cost:
- Find every owned type that holds a pointer to the heap:
String,Vec,Box,Rc,Arc,HashMapand the like. - Ask where each one is created. Creation is where
allocis called. - Ask how often that line runs. A single allocation at startup is irrelevant. The same allocation per request, per line or per element is not.
Not every allocation should be removed. Allocation is a normal tool, and removing it often makes code harder to read. The remaining chapters give you ways to find the allocations that matter and the techniques to remove them.
Exercise
A function builds let mut names: Vec<String> = Vec::new(); and then, in a loop that runs 1000 times, pushes format!("user-{}", i). Roughly how many calls to the allocator does the loop make, and which part of that number can be reduced by changing only the Vec line?
Show answer
About 1000 allocations come from format!, one String per iteration. The Vec itself grows geometrically, so it adds only about 8 more allocations (capacities 4, 8, 16, and so on up to 1024). Replacing Vec::new() with Vec::with_capacity(1000) removes those roughly 8 growth allocations and leaves one for the buffer. The 1000 String allocations remain, because each string owns its own heap block.
Exercise
Why is size_of::<Vec<u32>>() the same (24 bytes on a 64-bit target) for an empty vector and for a vector holding a million elements?
Show answer
A Vec value is only a handle: a pointer to the heap buffer, a length and a capacity. The million elements live in the heap buffer, outside the 24 bytes. size_of reports the size of the handle, not the data it points to.