Sub topic 12
Arena allocation for many short-lived objects
This chapter assumes you know ownership, lifetimes, and how Vec and Box allocate. It also assumes you can measure allocation counts, as covered earlier in this tutorial.
The problem arenas solve
Some programs create thousands of small objects that all die together. Examples are the nodes of a syntax tree for one file, or the temporary values used while handling one request. With Box, each node is a separate call to the global allocator, and each node is freed on its own at the end.
An arena (also called a bump allocator) grabs one large block of memory and hands out pieces of it by moving a pointer forward. Allocating is a pointer bump, with no free list to search. You free everything at once by dropping or resetting the arena.
A tree built in an arena
The bumpalo crate provides Bump. Add bumpalo = "3" to Cargo.toml. Nodes can hold plain shared references to each other, because the arena owns them all and they share one lifetime.
use bumpalo::Bump;
enum Expr<'a> {
Num(i64),
Add(&'a Expr<'a>, &'a Expr<'a>),
}
fn build<'a>(bump: &'a Bump, n: i64) -> &'a Expr<'a> {
let mut acc: &'a Expr<'a> = bump.alloc(Expr::Num(0));
for i in 1..=n {
let leaf = bump.alloc(Expr::Num(i));
acc = bump.alloc(Expr::Add(acc, leaf));
}
acc
}
fn eval(e: &Expr) -> i64 {
match e {
Expr::Num(n) => *n,
Expr::Add(a, b) => eval(a) + eval(b),
}
}
fn main() {
let mut bump = Bump::new();
for _ in 0..3 {
let tree = build(&bump, 1000);
println!("sum = {}", eval(tree));
bump.reset();
}
}Each pass creates about 2,000 nodes. After the first pass, reset keeps the memory, so later passes usually need no new requests to the global allocator. This also applies the buffer-reuse idea from earlier in the tutorial.
Without the arena, the same tree would need Box<Expr> fields and one heap allocation per node.
What you give up
Arenas trade flexibility for speed. Know these limits before you adopt one:
- No per-object freeing. Memory is returned only when the whole arena is reset or dropped. A long-lived arena that keeps allocating will keep growing.
- Destructors may not run.
Bump::allocdoes not callDropon its contents. Types that own heap data, such asStringorVec, leak that data unless you usebumpalo::boxed::Boxor the crate's collections. Prefer plain data in an arena. - Lifetimes spread. Every type that points into the arena carries
'a. Return values cannot outlive the arena. resetneeds&mut. The borrow checker will reject a reset while any reference into the arena is still alive. That is the safety guarantee working as intended.
When to choose an arena
Use an arena when many objects share one lifetime and are created in bursts. Compilers, parsers, game frames, and per-request scratch data fit this pattern.
Skip it when objects have independent lifetimes, when a few large objects dominate, or when profiling shows the allocator is not a bottleneck. A simpler fix, such as with_capacity or a SmallVec, often gets most of the gain. Measure with the counting allocator before and after, because an arena only helps if allocation count or time actually drops.
Exercise
A server builds a tree of about 5,000 nodes for each request, uses it, and discards it. Nodes contain only integers and references to other nodes. Why is a reused Bump a good fit, and what must you do between requests?
Show answer
All nodes share one lifetime (the request) and contain no types that need Drop, so a bump arena replaces about 5,000 allocator calls with pointer bumps. Between requests, call reset() on the arena. This needs &mut Bump, so no reference into the old tree may still be alive. The retained memory is reused by the next request.