Global allocators
Allocators are the way that programs in Rust obtain memory from the system atruntime. Previously, Rust did not allow changing the way memory is obtained,which prevented some use cases. On some platforms, this meant using jemalloc,on others, the system allocator, but there was no way for users to controlthis key component. With 1.28.0, the #[global_allocator]
attribute is nowstable, which allows Rust programs to set their allocator to the systemallocator, as well as define new allocators by implementing the GlobalAlloc
trait.
The default allocator for Rust programs on some platforms is jemalloc. Thestandard library now provides a handle to the system allocator, which can beused to switch to the system allocator when desired, by declaring a staticand marking it with the #[global_allocator]
attribute.
use std::alloc::System;
#[global_allocator]
static GLOBAL: System = System;
fn main() {
let mut v = Vec::new();
// This will allocate memory using the system allocator.
v.push(1);
}
However, sometimes you want to define a custom allocator for a givenapplication domain. This is also relatively easy to do by implementing theGlobalAlloc
trait. You can read more about how to do this in thedocumentation.