How to Use Arena Allocation in Rust

Use the bumpalo crate to create a Bump arena and allocate values with bump.alloc() for fast, bulk memory management.

Rust does not have a built-in arena allocator; you must use the bumpalo crate to allocate memory in a single block and free it all at once. Add bumpalo to your Cargo.toml, create a Bump instance, and use its alloc method to place values on the arena instead of the standard heap.

use bumpalo::Bump;

fn main() {
    let bump = Bump::new();
    let x = bump.alloc(42);
    let y = bump.alloc("hello");
    // Memory is freed automatically when `bump` goes out of scope
}
  1. Add the dependency to your project: cargo add bumpalo
  2. Import the allocator in your code: use bumpalo::Bump;
  3. Create a new arena instance: let bump = Bump::new();
  4. Allocate values into the arena: let x = bump.alloc(value);
  5. Let the arena drop to free all memory at once: drop(bump);