Expand description
Stalloc (Stack + alloc) is a fast first-fit memory allocator. From my benchmarking,
it can be over 3x as fast as the default OS allocator! This is because all memory
is allocated from the stack, which allows it to avoid all OS overhead. Since it
doesn’t rely on the OS (aside from SyncStalloc), this library is no_std compatible.
use stalloc::SyncStalloc;
// Create a global allocator with 1000 blocks, each 4 bytes in length.
#[global_allocator]
static GLOBAL: SyncStalloc<1000, 4> = SyncStalloc::new();
fn main() {
// All of these allocations are being handled by the global `SyncStalloc` instance.
let s1 = String::from("Hello");
let s2 = String::from("world");
let msg = format!("{s1}, {s2}!");
assert!(!GLOBAL.is_oom());
println!("Allocator state: {GLOBAL:?}");
}To avoid the risk of OOM, you can “chain” your allocator to the system allocator, using it as a fallback.
use stalloc::{AllocChain, SyncStalloc};
use std::alloc::System;
#[global_allocator]
static GLOBAL: AllocChain<SyncStalloc<1000, 8>, System> = SyncStalloc::new().chain(&System);§Feature flags
std(on by default) — used in the implementation ofSyncStallocallocator-api(requires nightly)allocator-api2(pulls in theallocator-api2crate)
Structs§
- Align
- A ZST with a given alignment.
AlignandAlignmentare used to ensure thatBlock, and henceStalloc, are aligned to a particular value. - Alloc
Chain - A chain of allocators. If the first allocator is exhuasted, the second one is used as a fallback.
- Stalloc
- A fast first-fit memory allocator.
- Stalloc
Guard - A lock around
SyncStalloc. Constructing this type is proof that the user holds an exclusive lock on the innerUnsafeStalloc. When this falls out of scope, theSyncStallocis unlocked. - Sync
Stalloc - A wrapper around
UnsafeStallocthat is safe to create because it prevents data races using a Mutex. In comparison toUnsafeStalloc, the mutex may cause a slight overhead. - Unsafe
Stalloc - A wrapper around
Stallocthat implements bothSyncandGlobalAlloc.
Traits§
- Chainable
Alloc - A trait representing an allocator that another allocator can be chained to.