Sub topic 14
Swapping the global allocator and when it helps
This chapter assumes you can read GlobalAlloc code like the counting allocator from the measuring chapter. It also assumes you can run cargo build --release and cargo bench. It is the last chapter in the series, so it comes after you have already removed the allocations you can.
What the global allocator does
Every Vec, String and Box asks the global allocator for memory. By default Rust uses the system allocator: glibc malloc on Linux, the system heap on Windows, and libc malloc on macOS. You can replace it with one #[global_allocator] static. Your code does not change.
A different allocator does not reduce the number of allocations. It changes what each one costs. The costs it can change are:
- the time of a single
allocordealloccall - contention when many threads allocate at once
- fragmentation, which affects resident memory over a long run
- memory returned to the operating system
Swapping in mimalloc
Add the crate to Cargo.toml:
[dependencies]
mimalloc = "0.1"Then declare it once in your binary crate:
use mimalloc::MiMalloc;
use std::thread;
use std::time::Instant;
#[global_allocator]
static GLOBAL: MiMalloc = MiMalloc;
fn work() -> usize {
let mut total = 0;
for i in 0..200_000 {
let s = format!("item-{}", i);
total += s.len();
}
total
}
fn main() {
let start = Instant::now();
let handles: Vec<_> = (0..4).map(|_| thread::spawn(work)).collect();
let total: usize = handles.into_iter().map(|h| h.join().unwrap()).sum();
println!("total = {}, elapsed = {:?}", total, start.elapsed());
}Run it with cargo run --release. Then delete the use mimalloc line and the two #[global_allocator] lines, and run it again. The difference between the two timings is the effect of the allocator on this workload. Run each version several times, because one run is noisy.
tikv-jemallocator follows the same pattern with use tikv_jemallocator::Jemalloc; and static GLOBAL: Jemalloc = Jemalloc;. It does not support every target, and MSVC Windows is the usual exception.
When it helps
A swap pays off most when the following are true:
- Many threads allocate and free small objects at the same time, so the default allocator's locks become a bottleneck.
- A long-running service shows resident memory growing from fragmentation.
- Profiling shows a large share of time inside
mallocandfree, and you cannot remove those calls.
It helps little when the program allocates rarely, or when it is bound by I/O or computation. In those cases, removing allocations with borrowing, Cow or buffer reuse will do more.
Common problems
- Measuring a debug build. Allocator differences are only meaningful with
--release. - Judging by one benchmark. An allocator that wins a threaded microbenchmark can lose on your real service. Test with real input.
- Ignoring memory. Some allocators keep freed memory cached for speed. Compare peak resident memory as well as time.
- Declaring two allocators. A program can have only one
#[global_allocator]. Dependencies should not declare their own, so put it in the final binary crate only. - Build requirements. These crates compile C code, so they may need a C toolchain in your build environment.
Decision criteria
Change the allocator last. Fix hidden allocations first, since each one you remove saves the whole cost of the call. Then measure. Keep the swap only if it improves a number you care about, such as throughput, tail latency or peak memory, and record the benchmark so the next person can repeat it.
Exercise
A service spends 3% of its time in malloc and free, and 40 threads contend on the default allocator's locks. Another service spends 30% of its time in malloc, mostly from calls to .to_string() inside a loop. Which one should try a new allocator first, and what should the other do?
Show answer
The first service should try a new allocator such as mimalloc or jemalloc, and benchmark it. Its allocation time is small, but the problem is thread contention, which is the case an allocator change can fix. The second service should remove the to_string allocations by borrowing, reusing a buffer, or writing into an existing String. Removing 30% of malloc time is worth more than making each call faster.