Jemallocator: Rust jemalloc Memory Allocator Alternative
The default allocator may sometimes fail to release memory promptly. It is recommended to use jemallocator as a global allocator to replace the default one.
jemallocator is a library linked with the jemalloc memory allocator, providing the Jemalloc unit type that implements the allocator API and can be set as #[global_allocator].
tikv-jemallocator is the successor project to jemallocator. These two crates are identical except for their names. For new projects, it is recommended to use the tikv-xxx version.
jemalloc Ecosystem
The jemalloc support ecosystem consists of the following crates:
- tikv-jemalloc-sys: Builds and links to jemalloc, exposing raw C bindings to it.
- tikv-jemallocator: Provides the
Jemalloctype that implements theGlobalAllocandAlloctraits. - tikv-jemalloc-ctl: High-level wrappers for jemalloc control and introspection APIs (the
mallctl*()function family andMALLCTL NAMESPACE).
Usage
Adding Dependencies
To use tikv-jemallocator, add it as a dependency:
Setting as Global Allocator
To set tikv_jemallocator::Jemalloc as the global allocator, add the following code to your project:
That's it! Once this static variable is defined, jemalloc will be used for all memory allocations requested by Rust code within the same program.
Advantages
jemalloc is a general-purpose malloc implementation focusing on:
- Reducing memory fragmentation
- Scalability in high-concurrency scenarios
- Providing rich introspection and control capabilities
It is particularly useful in the following scenarios:
- Long-running applications
- Memory-intensive workloads
- High-performance services requiring fine-grained memory management
Compatibility Notes
jemalloc does not support the MSVC target environment and is therefore unavailable when using the MSVC toolchain on Windows. This is why the cfg(not(target_env = "msvc")) condition is included in the example code.