stack-arena
A fast, stack-like arena allocator for efficient memory management, implemented in Rust.
Features
- Efficient allocation of variable-sized objects with minimal overhead
- Memory is managed in chunks, automatically growing when needed, with old chunks preserved to maintain pointer validity
- Stack-like (LIFO) allocation and deallocation pattern
- Low-level memory management with minimal overhead
- Automatic chunk reuse for improved performance
- Implements the
Allocatortrait for compatibility with allocation APIs - Suitable for parsers, interpreters, and other high-performance scenarios
When to Use
Stack-arena is ideal for scenarios where:
- You need to allocate many small objects in sequence
- Objects follow a stack-like (LIFO) allocation/deallocation pattern
- Memory usage needs to be minimized with low per-allocation overhead
- Performance is critical, especially for parsers, interpreters, or compilers
- You want to avoid the overhead of the system allocator for short-lived objects
Architecture
The library is organized in layers:
Chunk- The lowest level, representing a contiguous region of memoryBufferArena- Manages a single memory chunk with bump allocationStackArena- Manages multiple chunks with LIFO allocation/deallocationObjectStack- High-level interface for building objects incrementally
Getting Started
Add to your Cargo.toml:
[]
= "0.11"
Using ObjectStack (high-level API)
The ObjectStack provides a user-friendly interface for building and managing objects:
use ObjectStack;
use Write;
let mut stack = new;
// Push a complete object
stack.push;
// Build an object incrementally
stack.extend;
write!.unwrap;
let ptr = stack.finish;
// Access the object
let hello_world = unsafe ;
assert_eq!;
// Pop the object when done
stack.pop;
Using StackArena (low-level API)
The StackArena provides more control over memory allocation:
use ;
use Layout;
// Create with default chunk size (4096 bytes)
let mut arena = new;
// Or create with a custom chunk size
let mut custom_arena = with_chunk_size;
// Allocate memory
let layout = from_size_align.unwrap;
let ptr = unsafe ;
// Use the memory...
unsafe ;
// Deallocate when done
unsafe ;
Performance
The library is optimized for scenarios with many small allocations that follow a stack-like pattern. Benchmarks show it significantly outperforms the system allocator in these cases:
- Up to 10x faster for consecutive small allocations
- Minimal overhead for allocation and deallocation
- Efficient memory reuse with the LIFO pattern
- Reduced memory fragmentation
Safety
- All returned pointers are valid until the corresponding object is deallocated
- Objects are stored in contiguous memory chunks
- Unsafe operations are used internally for performance
- The library follows LIFO (Last-In-First-Out) allocation pattern for efficiency
- Users must ensure proper memory safety when working with raw pointers
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
MIT