Sub topic 12
Arena allocation for many short-lived objects
This chapter assumes you know ownership and lifetimes, the Vec/String/Box basics, and how to measure allocations with the counting allocator from earlier in this tutorial. It also assumes you can add a crate to Cargo.toml.
The problem arenas solve
Some programs build many small objects that all die together. A compiler builds a syntax tree for one file, then throws it away. A web server builds request-scoped data and drops it when the response is sent. A game builds per-frame scratch data.
If each object is a Box, each one is a separate call to the global allocator. Each box is also freed individually when the owner drops. That costs time for the allocator bookkeeping, and the nodes end up scattered in memory, which hurts cache locality.
An arena (also called a bump allocator) is a large block of memory from which you hand out pieces by moving a pointer forward. Allocating is "round the pointer up to the right alignment, add the size, check there is room". Individual objects are never freed. The whole arena is freed or reset at once.
The trade-off is clear. You get very cheap allocation and one cheap bulk free. You give up freeing single objects early, so memory use only goes down at the reset.
Option 1: an index-based arena with only std
You do not need a crate to get most of the benefit. A Vec that owns all the nodes, plus small integer handles instead of pointers, is an arena. Nodes refer to each other by index.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ExprId(u32);
#[derive(Debug)]
enum Expr {
Num(i64),
Add(ExprId, ExprId),
Mul(ExprId, ExprId),
}
struct ExprArena {
nodes: Vec<Expr>,
}
impl ExprArena {
fn with_capacity(n: usize) -> Self {
ExprArena { nodes: Vec::with_capacity(n) }
}
fn alloc(&mut self, e: Expr) -> ExprId {
let id = ExprId(self.nodes.len() as u32);
self.nodes.push(e);
id
}
fn eval(&self, id: ExprId) -> i64 {
match &self.nodes[id.0 as usize] {
Expr::Num(n) => *n,
Expr::Add(a, b) => self.eval(*a) + self.eval(*b),
Expr::Mul(a, b) => self.eval(*a) * self.eval(*b),
}
}
fn clear(&mut self) {
self.nodes.clear();
}
}
fn main() {
let mut arena = ExprArena::with_capacity(16);
// (2 + 3) * 4
let two = arena.alloc(Expr::Num(2));
let three = arena.alloc(Expr::Num(3));
let sum = arena.alloc(Expr::Add(two, three));
let four = arena.alloc(Expr::Num(4));
let product = arena.alloc(Expr::Mul(sum, four));
println!("result = {}", arena.eval(product));
// Reuse the same memory for the next tree.
arena.clear();
println!("nodes after clear = {}", arena.nodes.len());
}This design has useful properties:
- With
with_capacity, building the tree makes no allocations until the capacity is exceeded. After that,Vecreallocates as usual. cleardrops the nodes and keeps the capacity, so the next tree reuses the same memory.- Handles are
Copyand 4 bytes, smaller than a 8-byte pointer on 64-bit targets. No lifetimes appear in your types. - Because indices instead of references link nodes, there are no borrow checker fights when you mutate the tree.
The costs: an ExprId from one arena is meaningless in another, and nothing stops you from using a stale id after clear. It would panic on an out-of-range index, or silently point at a new node. Also, all nodes must be the same type. Here that is one enum.
Option 2: a bump arena with references
When you want ordinary references (&'a Expr<'a>) and mixed types in one arena, use a crate. bumpalo is the common choice. Add it to Cargo.toml:
[dependencies]
bumpalo = "3"use bumpalo::Bump;
enum Expr<'a> {
Num(i64),
Add(&'a Expr<'a>, &'a Expr<'a>),
Mul(&'a Expr<'a>, &'a Expr<'a>),
}
fn eval(e: &Expr<'_>) -> i64 {
match e {
Expr::Num(n) => *n,
Expr::Add(a, b) => eval(a) + eval(b),
Expr::Mul(a, b) => eval(a) * eval(b),
}
}
fn build_and_eval(bump: &Bump, x: i64) -> i64 {
let a = bump.alloc(Expr::Num(x));
let b = bump.alloc(Expr::Num(3));
let sum = bump.alloc(Expr::Add(a, b));
let four = bump.alloc(Expr::Num(4));
let product = bump.alloc(Expr::Mul(sum, four));
let label: &str = bump.alloc_str("scratch label");
debug_assert!(!label.is_empty());
eval(product)
}
fn main() {
let mut bump = Bump::new();
for round in 0..3 {
let value = build_and_eval(&bump, round);
println!("round {round}: {value}");
// All references into the arena are gone, so reset is allowed.
bump.reset();
}
}Points to notice:
bump.alloctakes&self, not&mut self. You can hold many references into the arena at once. The arena uses interior mutability to move its pointer.bump.reset()takes&mut self. The borrow checker therefore rejects a reset while any reference into the arena is still alive. That is the safety guarantee. The function returns ani64, which owns no arena memory, so the reset compiles.resetkeeps the largest chunk and frees the rest, so a steady workload stops hitting the system allocator after the first round or two.- Every reference carries the lifetime
'aof the arena borrow. That lifetime spreads into your types, such asExpr<'a>, and into function signatures. This is the main ergonomic cost compared with indices.
The typed-arena crate is a similar option when all values have one type. It runs Drop for them when the arena drops.
What an arena does not do
Destructors may not run
bumpalo::Bump does not call Drop on values you place in it. That is fine for plain data such as integers, &str, and enums of references. It is a leak if a value owns heap memory. A Vec<u8> or String placed in the arena would keep its own heap buffer and never free it. Use bumpalo::collections::Vec and String (behind the crate's collections feature), which store their buffers in the arena, or keep owning types out of it.
Memory is not returned until reset
Short-lived objects inside a long-lived arena pile up. If a server uses one arena for its whole lifetime and allocates per request, memory grows without bound. Tie the arena to the unit of work, and reset it at the end of that unit.
One huge value can inflate the arena
Arenas grow by chunks. After a rare large request, the chunk stays until the arena is dropped. If peak size varies wildly, drop and recreate the arena now and then instead of resetting it forever.
Results must leave the arena
Anything you return past the reset must be owned elsewhere. Convert it to an owned String or struct before you drop the arena. This one copy is usually far cheaper than thousands of per-node frees.
Choosing between the options
| Approach | Allocation cost | Lifetimes in your types | Mixed types | Individual free | Best for |
|---|---|---|---|---|---|
| `Box` per node | One allocator call each | No | Yes (via enums or `dyn`) | Yes | Small trees, clarity first |
| `Vec<T>` plus index handles | Amortized, none after warm-up | No | One type | No (clear all) | Graphs and trees of one node type |
| `bumpalo::Bump` | Pointer bump | Yes | Yes | No (reset all) | Compilers, request-scoped data |
| `typed-arena` | Pointer bump | Yes | One type per arena | No | Self-referential graphs, with `Drop` support |
Check that it helped
Do not adopt an arena on a guess. Use the counting allocator from the measurement chapter around the code that builds the structure. Compare the allocation count with Box against the count with the arena. For a tree of N nodes you should see N calls fall to a small number, roughly the number of chunks the arena grabbed.
Then check wall-clock time with cargo bench or a profiler. If the allocator was not a hotspot, the arena adds a lifetime parameter for little gain. Arenas pay off when you create tens of thousands of small objects per unit of work, or when freeing them one by one shows up in a profile.
Summary
- An arena replaces many individual allocations with pointer bumps and frees everything at once.
- Index handles into a
Vecgive you an arena with std only. A bump allocator such asbumpalogives you references and mixed types at the cost of lifetime parameters. resetandclearkeep memory for reuse, so tie the arena to a unit of work.- Watch for skipped destructors, growth in long-lived arenas, and results that must be copied out.
- Confirm the gain by counting allocations and timing the code before and after.
Exercise
A server builds a parse tree for each incoming request using bumpalo::Bump. A teammate keeps one Bump in a global for the life of the process and never resets it, because "arenas are cheap". After a day, memory use is very high. What is wrong, and how do you fix it? Also, one node type holds a String field copied from the request. What extra problem does that cause?
Show answer
The arena only frees memory when it is reset or dropped, so a process-lifetime arena grows with every request. Fix it by creating the Bump per request (or calling reset() after each request, once no references into it remain). The String field is a second problem: Bump does not run Drop, so the String's own heap buffer is never freed, even after a reset. Store &'a str allocated with bump.alloc_str, or use bumpalo::collections::String, so the text lives in the arena.
Exercise
In the index-based ExprArena, what happens if you call arena.clear() and then call arena.eval(product) with an old ExprId? Name one way to make this class of bug harder to hit.
Show answer
The old id indexes into a Vec that is now empty, so self.nodes[id.0 as usize] panics with an out-of-bounds error. If you had built a new tree first, the old id could instead point at an unrelated node and return a wrong answer silently. To make it harder to hit, add a generation counter to the arena and store it in each id so eval can reject stale ids, or tie ids to a borrow of the arena so they cannot outlive a clear.