Sub topic 14
Swapping the global allocator and when it helps
This chapter assumes you know how #[global_allocator] works from the chapter on measuring allocations. It also assumes you can run cargo build --release and compare two builds with a benchmark. Earlier chapters removed allocations from your code. This chapter covers the opposite option: keep the allocations and make each one cheaper.
What the global allocator does
Every Vec, String, Box and Rc in a Rust program gets its memory from one place, the global allocator. By default that is the system allocator, reached through the System type. On Linux with glibc it is malloc. On Windows it is the process heap. On macOS it is the system malloc zone.
Rust lets you replace it with one static item marked #[global_allocator]. The item must implement GlobalAlloc. Nothing else in your code changes. Calls to Vec::push, Box::new and String::from all route to the new allocator.
Allocators differ in these ways:
- Speed of small allocations. Some keep per-thread caches, so an allocation takes no lock.
- Behavior under many threads. A single shared lock or arena becomes a bottleneck when many threads allocate at once.
- Fragmentation. Long-running programs with mixed object sizes can leave unusable gaps in memory.
- Returning memory to the OS. Some allocators release freed pages eagerly, and others hold them for reuse.
- Diagnostics. Some provide heap profiling and statistics.
The common replacements
| Allocator | Crate | Typical strength | Caveats |
|---|---|---|---|
| mimalloc | `mimalloc` | Fast small allocations, simple to adopt, works on Windows, macOS and Linux | Needs a C compiler at build time |
| jemalloc | `tikv-jemallocator` | Good multithreaded behavior, low fragmentation, built-in statistics and profiling | Not supported on MSVC targets, and tuning options are numerous |
| System | built in | No extra dependency, smallest binary, behaves predictably with OS tools | Quality varies by platform. musl's allocator is known to be slow under threads |
Adopting one takes a dependency and three lines. Here is mimalloc:
[dependencies]
mimalloc = "0.1"use mimalloc::MiMalloc;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
fn main() {
let v: Vec<u64> = (0..10).collect();
println!("{:?}", v);
}For jemalloc, the dependency is tikv-jemallocator and the static looks like this:
use tikv_jemallocator::Jemalloc;
#[global_allocator]
static GLOBAL: Jemalloc = Jemalloc;
fn main() {
let s = String::from("allocated by jemalloc");
println!("{}", s);
}Compare allocators with a benchmark
Do not adopt an allocator because of a blog post. Allocator performance depends on allocation sizes, thread count, lifetimes and the OS. Make the allocator a build-time switch, then run your real workload under each choice.
This program is an allocation-heavy workload on eight threads. It creates many short-lived strings, which stresses the small-allocation path. The mimalloc feature selects the allocator.
[package]
name = "alloc-compare"
version = "0.1.0"
edition = "2021"
[features]
mimalloc = ["dep:mimalloc"]
[dependencies]
mimalloc = { version = "0.1", optional = true }use std::thread;
use std::time::Instant;
#[cfg(feature = "mimalloc")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
fn churn(rounds: usize) -> usize {
let mut total = 0;
for i in 0..rounds {
let items: Vec<String> = (0..16).map(|j| format!("item-{i}-{j}")).collect();
total += items.iter().map(|s| s.len()).sum::<usize>();
}
total
}
fn main() {
let start = Instant::now();
let handles: Vec<_> = (0..8)
.map(|_| thread::spawn(|| churn(200_000)))
.collect();
let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("total = {total}, elapsed = {:?}", start.elapsed());
}Run both builds in release mode:
cargo run --release
cargo run --release --features mimallocRun each several times and compare medians, not single runs. Use the same machine, and close other heavy programs. If the difference is within run-to-run noise, the allocator is not your bottleneck.
Count versus cost
An allocator swap and an allocation reduction fix different problems. The table shows which one fits.
| Symptom | Better fix |
|---|---|
| Profile shows a hot loop calling `malloc` millions of times for identical sizes | Preallocate, reuse buffers, or use an arena (removes the calls) |
| Many threads, throughput does not scale, time is spent waiting in the allocator | Swap the allocator (makes calls cheaper under contention) |
| Memory use grows over days even though live data is stable | Try an allocator with better fragmentation behavior, and check for leaks first |
| Slow only on musl targets | Swap the allocator |
| Allocation is under 1% of a CPU profile | Neither. Look elsewhere |
An allocator swap does not change your allocation counts. The counting allocator from earlier chapters would report the same number of calls. Each call is simply faster or slower. A count reduction also removes the cost of initializing, touching and freeing that memory. So reduce counts first when you can, and swap the allocator when the remaining cost is spread across the program and no single site is worth rewriting.
Gotchas
Memory reported by the OS may look different
Allocators keep freed memory for reuse and return it to the OS on their own schedule. After a swap, resident set size (RSS, the physical memory the OS charges to your process) can go up or down even if your program's live data is the same. Judge memory by a long-running soak test, not by one snapshot. A higher number right after a burst of work may be reusable cache, not a leak.
Wrapping an allocator
Your counting allocator from earlier chapters can sit on top of a replacement. Wrap the replacement instead of System, and the counts stay available. This is useful for confirming that a swap really did not change call counts.
use mimalloc::MiMalloc;
use std::alloc::{GlobalAlloc, Layout};
use std::sync::atomic::{AtomicUsize, Ordering};
struct Counting;
static ALLOCS: AtomicUsize = AtomicUsize::new(0);
unsafe impl GlobalAlloc for Counting {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
ALLOCS.fetch_add(1, Ordering::Relaxed);
unsafe { MiMalloc.alloc(layout) }
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
unsafe { MiMalloc.dealloc(ptr, layout) }
}
}
#[global_allocator]
static GLOBAL: Counting = Counting;
fn main() {
let before = ALLOCS.load(Ordering::Relaxed);
let v: Vec<u32> = (0..1000).collect();
let after = ALLOCS.load(Ordering::Relaxed);
println!("len = {}, allocations = {}", v.len(), after - before);
}Memory crossing a foreign function boundary
Memory allocated by Rust's global allocator must be freed by the same allocator. If you hand a Box pointer to C code and C calls free on it, the program is undefined. This was already wrong with the system allocator in many cases. After a swap it is more likely to crash, because the allocators no longer share a heap. Free Rust memory in Rust, and C memory with C's free, or use the library's own release function.
Build and platform constraints
- mimalloc compiles C code, so builds need a C toolchain. This can complicate cross-compiling.
tikv-jemallocatordoes not support MSVC targets. Gate it with#[cfg(not(target_env = "msvc"))]if you build for Windows too.- Binary size grows by a small amount, which matters on embedded or WebAssembly targets. Many such targets need a different allocator anyway, so check the target's documentation.
- Sanitizers and tools like Valgrind work best with the system allocator. If you rely on them, keep a feature switch so debugging builds can use
System.
Benchmarks that mislead
- Microbenchmarks that allocate and free the same size in a loop favor allocators with a fast thread-local cache. Real programs with mixed sizes and long lifetimes may not see the same gain.
- Single-threaded programs rarely benefit from the contention improvements that justify a swap.
- A debug build says nothing about release behavior. Always use
--release.
Decision criteria
Adopt a replacement allocator when all of these hold:
- A profile on a realistic workload shows allocation or deallocation as a meaningful share of time, or memory growth caused by fragmentation.
- Remaining allocation sites are too numerous or too scattered to remove with the earlier techniques.
- A benchmark of your actual workload shows a gain larger than the run-to-run noise.
- The build and platform constraints above are acceptable for your deployment.
Keep the benchmark in your repository. Allocator behavior changes between versions, and your workload will change as well. Re-run the comparison after major dependency updates or workload shifts.
Exercise
A service runs on 32 threads and a CPU profile shows 12% of time inside malloc and free, spread over hundreds of call sites. No single site is above 1%. Should you first rewrite call sites to reduce allocations, or benchmark a different global allocator? Explain.
Show answer
Benchmark a different allocator first. The cost is spread across hundreds of sites, so rewriting any one of them gains under 1%. Heavy threading suggests contention in the default allocator, which mimalloc or jemalloc may reduce. Adopt it only if a benchmark on the real workload shows a gain beyond noise. Afterwards, profile again. If a few sites now stand out, apply the earlier techniques there.
Exercise
You replace the system allocator with mimalloc and your counting allocator, wrapped around it, reports the same allocation count as before. Is the swap broken?
Show answer
No. A global allocator swap changes how each call is served, not how many calls the program makes. The count stays the same. Only wall-clock time, memory behavior or contention should change, so check those with a benchmark.
Exercise
A teammate adds #[global_allocator] with jemalloc inside a shared library crate that other services depend on. Why is this a problem?
Show answer
The attribute applies to the whole final binary, and a binary can have only one global allocator. If the library sets it, any application that also sets one fails to compile, and applications that did not want jemalloc get it anyway. It can also break builds on MSVC targets. The final application should choose the allocator.