To use jemalloc or mimalloc in Rust, enable the corresponding feature flag in your Cargo.toml and add the allocator to your binary entry point.
For rust-analyzer or similar tools, add the feature to the dependency and use the #[global_allocator] attribute in src/bin/main.rs:
[dependencies]
mimalloc = { version = "0.1.46", default-features = false, optional = true }
jemallocator = { version = "0.5.4", package = "tikv-jemallocator", optional = true }
[features]
mimalloc = ["dep:mimalloc"]
jemalloc = ["dep:jemallocator"]
#[cfg(feature = "mimalloc")]
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
#[cfg(all(feature = "jemalloc", not(target_env = "msvc")))]
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;
fn main() {
// Your application logic
}
For building the Rust compiler itself with jemalloc, set the feature in bootstrap.toml:
[build]
rust.jemalloc = true
Then run ./x.py build.