A memory allocator is the intermediary between a running program and the operating system. It manages requests for dynamic memory, returns usable storage, and releases storage that is no longer needed. Allocators can optimize these operations by avoiding repeated work in the OS and CPU. section 6.3.3
Dynamic allocation follows three steps: request memory from the operating system, use it in the program, and release it. Heap data is flexible because pointers can change, but access is generally slower than stack access because heap values may be non-contiguous and require pointer dereferencing. section 6.3.3
Reporting allocations in Rust
A Rust program can install a custom global allocator by implementing GlobalAlloc and delegating to System. The allocator can measure each allocation with Instant, while a graphical particle program creates and destroys heap objects. Running it with cargo run -q 2> alloc.tsv records allocation data for inspection.
Allocation time is difficult to predict: measurements show no clear relationship between requested size and duration, even for repeated requests of the same size. This makes measurement important when allocation costs matter. section 6.3.4
Ways to reduce heap-allocation overhead include:
- Reuse arrays of uninitialized objects instead of creating objects whenever they are needed, while recognizing that bypassing Rust lifetime checks can be dangerous. section 6.3.4
- Choose an allocator tuned to the application's memory-access profile, because allocators often perform best for particular allocation sizes. section 6.3.4
- Use arena or TypedArena allocation when suitable; allocation and freeing then occur when the arena is created and destroyed. section 6.3.4

