文章标题:2026 年分配器现状——终于稳定了
正文: 距离上一篇文章才过了几个月,我很高兴地看到,在经历了 10 年的悬而未决之后,分配器终于稳定了!虽然 never 类型似乎确实抢走了一些风头,但 rust 1.100 仍然是一个里程碑式的版本。祝贺推动此事完成的团队。
那么,现在我们有了分配器 API 的 MVP,能用它做什么呢?除了与其他系统级语言(如 C++ 和 Zig)的功能更趋一致之外,它能给我们带来什么?
在本文中,我将逐步介绍几个对普通 rust 程序员可能很方便的用例,希望你能从中看到好处。
分配器可以调整内存释放的时机
这是自定义分配的主要用例之一。在 rust 中 drop 并非没有代价。此前已有将内存移到专用线程来 Drop 高度嵌套结构的做法。但这实际上只是解决方案的一半。你仍然要付出释放调用的成本,只是它不再处于热路径上了。
那么,如果我们知道代码中会有一段时间,要分配大量东西,对它们做些处理,然后全部释放,会怎样呢?一个很好的例子是 web 请求或数据库查询。
一个请求进来,填充一些数据结构,然后当请求结束时,内存不再需要了,于是被释放。这种“突发”式的分配模式—— upfront 大量分配,然后在最后一次性拆除——相当常见。
为此我们可以使用 bump 分配器:预留一大块内存,从中分配,而不是为每次分配都付出与系统分配器打交道的成本。可以把它想象成 std io 的 BufReader 和 BufWriter,与其反复进行系统调用来获取数据,我们可以把数据缓冲在一个大块里,从而大幅减少开销。
想要更多内存?只需检查大小是否适合我们的块,返回那个切片,递增我们的计数器(bump!),就完成了。如果不够用,我们还可以添加更多块。这让分配变得非常廉价,除了一个计数器之外,我们不需要维护太多状态。
这种方法缺点在于我们释放内存的时候。我们不会跟踪各个分配是在哪里进行的。然而,这实际上解决了我们 drop 耗时过长的问题,因为我们可以一次性释放所有东西。
本质上,如果 bump 分配器的实现是:
const SIZE: usize = 32 * 1024 * 1024;
const LAYOUT: Layout = Layout::new::<[u8; SIZE]>();
struct Bump {
// one big 32MiB block from the global allocator
data: NonNull<u8>,
// how much of it we've handed out
used: Cell<usize>,
}
impl Bump {
fn new() -> Self {
let data = Global.allocate(LAYOUT).expect("out of memory").cast::<u8>();
Bump { data, used: Cell::new(0) }
}
}
impl Drop for Bump {
fn drop(&mut self) {
// hand the whole block back in one go
unsafe { Global.deallocate(self.data, LAYOUT) }
}
}
unsafe impl Allocator for &Bump {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
// where we are in memory
let data = self.data.as_ptr();
// how much we've used of `data` already
let used = self.used.get();
// given the requested alignment, how many bytes do we need past `data` + `used`
let alignment_padding = data.wrapping_add(used).align_offset(layout.align());
let start = used + alignment_padding;
let end = start + layout.size();
if end <= SIZE {
// bump!
self.used.set(end);
let ptr = unsafe { NonNull::new_unchecked(data.add(start)) };
return Ok(NonNull::slice_from_raw_parts(ptr, layout.size()));
}
// an actual bump allocator would grab another block here
Err(AllocError)
}
unsafe fn deallocate(&self, _ptr: NonNull<u8>, _layout: Layout) {
// deliberately a no-op!
}
}
然后我们可以这样使用它:
struct Node<'a> {
value: u64,
parent: Option<&'a Node<'a>>,
}
// our bump allocator
let bump = Bump::new();
// leak here gives us a ref tied to the arena, the memory still goes when we drop our allocator
let mut leaf: &Node = Box::leak(Box::new_in(Node { value: 0, parent: None }, &bump));
for i in 1..1_000_000 {
leaf = Box::leak(Box::new_in(Node { value: i, parent: Some(leaf) }, &bump));
}
// this takes virtually no time at all!
drop(bump);
在 bump allocator 中这样做有一些权衡,并不是每种分配都会受益。这就是为什么能够在局部而非仅仅全局地调整分配策略很重要。然而,细心的读者可能会注意到,如果我们 bump 大块内存,这可能会导致内存使用量大幅增加。那么,这就引出了下一节:内存核算。
分配器可以让我们知道它们在使用多少内存
自定义分配器可以解决的另一个挑战是了解特定代码段使用了多少内存。也就是说,内存核算。这里的关键是,我们可以使用现有的分配器,并加入一些额外的记账,以保持相当准确的账本。
核算可以影响代码行为的使用场景有很多。假设你有一个对象缓存,你想设置一个阈值,超过该阈值就开始驱逐条目。或者假设你想做外部排序,但一开始不知道数据结构有多大,而又想尽可能多地使用内存。或者也许你想对代码沙箱施加限制,因为它与其他沙箱共享资源。
你可以做的是,用一个自定义核算层包装分配器,并用它来驱动你的决策。也就是说,下面是一个非常简单的例子:
struct AccountedAllocator<A: Allocator> {
inner: A,
allocated: AtomicUsize,
}
impl<A: Allocator> AccountedAllocator<A> {
fn new(inner: A) -> Self {
Self { inner, allocated: AtomicUsize::new(0) }
}
fn allocated(&self) -> usize {
self.allocated.load(Ordering::Relaxed)
}
}
unsafe impl<A: Allocator> Allocator for &AccountedAllocator<A> {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
// pass the allocation through, and count it if it succeeded
let ptr = self.inner.allocate(layout)?;
self.allocated.fetch_add(layout.size(), Ordering::Relaxed);
Ok(ptr)
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
unsafe { self.inner.deallocate(ptr, layout) };
self.allocated.fetch_sub(layout.size(), Ordering::Relaxed);
}
}
然后我们可以包装全局分配器,看看我们的缓存使用了多少:
let accounted = AccountedAllocator::new(Global);
let mut cache: Vec<u8, _> = Vec::new_in(&accounted);
cache.extend_from_slice(&[0; 1024]);
// cache is using 1024 bytes
println!("cache is using {} bytes", accounted.allocated());
cache.extend_from_slice(&[0; 4096]);
// cache is using 5120 bytes
println!("cache is using {} bytes", accounted.allocated());
drop(cache);
// cache is using 0 bytes
println!("cache is using {} bytes", accounted.allocated());
无耻推销:Thresher crate
现在,单个 atomic 虽然对示例来说很好,但确实有一些性能开销。所以,我创建的其中一个 crate 在考虑性能的同时,就是 thresher:一个带阈值回调的核算分配器。它使用组合的“本地”任务/线程和“全局”计数器来避免 atomic 争用,每分配 64KiB 就反馈一次。
thresher 的名字来自最可爱的鲨鱼:Thresher Shark(长尾鲨)。
现在,你可以用 thresher 做的是,当分配达到阈值时触发回调:
let thresher = Thresher::new();
thresher.set_callback_threshold(100 * 1024 * 1024);
thresher.set_callback(|allocation| {
println!("Threshold reached! Allocated: {} bytes", allocation);
});
// This is what we're adding to our vec each loop
let bytes = vec![0u8; 10 * 1024 * 1024];
// The vec allocates through the handle, so its buffer counts towards the
// threshold. `bytes` above uses the global allocator and is not counted
let mut vec = Vec::<u8, _>::new_in(thresher.handle());
for i in 0..10 {
println!("Loop {i}, Vec Capacity: {}", vec.capacity());
vec.extend(&bytes);
}
它会打印出符合预期的结果:
Loop 0, Vec Capacity: 0
Loop 1, Vec Capacity: 10485760
Loop 2, Vec Capacity: 20971520
Loop 3, Vec Capacity: 41943040
Loop 4, Vec Capacity: 41943040
Loop 5, Vec Capacity: 83886080
Loop 6, Vec Capacity: 83886080
Loop 7, Vec Capacity: 83886080
Loop 8, Vec Capacity: 83886080
Threshold reached! Allocated: 167772160 bytes
Loop 9, Vec Capacity: 167772160
一个生产环境的用例是,我们在 logfire 上使用 thresher,以便在内存达到配置的阈值时,为我们的 Rust 服务提供堆内存分析。我在之前的一篇博客《a tale of two lengths》中深入探讨了堆分析以及它们为何极其有用。在 thresher 中你可以找到一个 jemalloc 示例,可以自己动手进行插桩!
好了,我们可以在内存被释放时控制它,我们可以使用内存核算来了解我们使用了多少内存,那还剩什么?它去了哪里?
分配器可以控制内存所在的位置
这大概是我想要给出的 3 个示例中比较深奥的一个。在某些情形下,你确实需要控制内存所在的位置,而有时通过一些分配技巧,你可以获得更好的性能。
在栈上分配
一个例子就是 smallvec 及其同类所做的。它们不会直接去堆上分配,而是有一小块内存位于栈上,只有当分配超过一定大小时,才会写入堆。
虽然 smallvec 经过了更多的实战检验,但这里有一些示例代码,展示如何用分配器 API 做到这一点:
const SIZE: usize = 8192;
struct SmallStack {
// store the first 8KiB on the stack
data: UnsafeCell<[MaybeUninit<u8>; SIZE]>,
// how much we've already allocated on our stack
used: Cell<usize>,
}
impl SmallStack {
fn new() -> Self {
Self {
data: UnsafeCell::new([MaybeUninit::uninit(); SIZE]),
used: Cell::new(0),
}
}
}
unsafe impl Allocator for &SmallStack {
fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> {
// where we are in memory
let data = self.data.get().cast::<u8>();
// how much we've used of `data` already
let used = self.used.get();
// given the requested alignment, how many bytes do we need past `data` + `used`
let alignment_padding = data.wrapping_add(used).align_offset(layout.align());
let start = used + alignment_padding;
let end = start + layout.size();
// if we have enough on our local stack:
if end <= SIZE {
self.used.set(end);
let ptr = unsafe { NonNull::new_unchecked(data.add(start)) };
Ok(NonNull::slice_from_raw_parts(ptr, layout.size()))
} else {
// otherwise allocate on the standard heap
Global.allocate(layout)
}
}
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
let data = self.data.get().addr();
// if this isn't an address in our data
if !(data..data + SIZE).contains(&ptr.as_ptr().addr()) {
unsafe { Global.deallocate(ptr, layout) };
}
}
}
然后我们就可以使用我们这个玩具级的栈优先分配器:
// needs to live longer than our vec
let stack = SmallStack::new();
let mut vec: Vec<u32, _> = Vec::new_in(&stack);
// fits in our stack data buffer
for i in 0..32 {
vec.push(i);
}
// 最终会溢出到堆上 for i in 32..10_000 { vec.push(i); }
瞧!我们在栈上进行了更小的分配,然后按需推入堆中。这可以带来一些不错的性能提升。
## 使用更强的对齐方式进行分配
通常当你对齐内存分配时,这是基于所分配的对象来决定的。也就是说,是 u64 吗?对齐到 8 字节,还是 u32?对齐到 4。如果没有正确对齐,这可能导致未定义行为以及各种问题。你会注意到在 bump 和小的栈分配示例中,我不得不做一些小把戏来找到下一个适当对齐的地址。然而,在某些场景中,内存的对齐要求与所分配的对象是无关的。
在 Linux 中,当你通过标准系统调用从磁盘读取任何内容时,通常是从内核的页缓存中读取。也就是说,内核周围的空闲内存使得一切透明地快速。大多数时候这没问题,但有些时候你想绕过它。
也就是说,Kubernetes 中有一个长期存在的 bug,如果你使用页缓存,可能会导致 pod 被驱逐。或者:如果你在做自己的缓存层,有时在专用于缓存文件的内存上再叠加一层就没有意义了。
所以,有一种退出机制,以 O_DIRECT 的形式提供,允许你直接从文件系统访问文件。然而:使用这个标志的要求之一是,你读取或写入的内存要对齐到设备的逻辑块大小。这通常是 512 的倍数,但根据硬件不同可能更小或更大。
块对齐分配器的实现非常简单,这里有一个我们直接硬编码为 4096 的示例:
#[derive(Clone, Copy)] struct BlockAligned;
// 这里硬编码,但我们也可以从设备本身派生出来! const BLOCK_SIZE: usize = 4096;
unsafe impl Allocator for BlockAligned { fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, AllocError> { let layout = layout.align_to(BLOCK_SIZE).map_err(|_| AllocError)?; Global.allocate(layout) }
unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) { let layout = layout.align_to(BLOCK_SIZE).expect("layout must come from BlockAligned"); unsafe { Global.deallocate(ptr, layout) } } }
有了这个,我们现在可以编写简单的代码来使用 O_DIRECT 直接读取:
let mut buf: Vec<u8, BlockAligned> = Vec::new_in(BlockAligned); buf.resize(BLOCK_SIZE, 0);
let mut file = OpenOptions::new() .read(true) .custom_flags(libc::O_DIRECT) .open(path)?;
file.read_exact(&mut buf)?;
在这里,如果我们没有使用块大小对齐的分配,read_exact 调用在某些设备上可能会失败。
就像栈优先分配一样,已经有库可以让你做到这一点,比如 aligned-vec crate,它们有自己的数据类型可以很好地配合工作。
但问题在于:假设你有一个应用程序,你想混合和搭配不同的分配策略:有些 vec 你希望是块对齐的,有些你希望分配在栈上,但你希望能够对两者使用共享方法。我们是否想使用 smallvec 和 aligned-vec 来处理本质上相同、只是分配方式不同的数据结构?
std 分配器允许你对集合进行泛型化,无论使用什么分配器:
fn do_something<A: Allocator>(my_vec: &mut Vec<u32, A>) {}
我认为这非常强大。
结论与总结
生态系统跟上自定义分配器的步伐还需要一段时间。许多流行的 crate 有 MSRV 政策,使它们甚至无法使用新的标准特性,而一些现有的 crate——我本以为它们会是新分配器 API 的必然之选——截至撰写本文时尚未提供支持。
文章标题:2026年分配器现状——终于稳定下来了
正文: libs 团队还没有完工。这是分配器的 MVP,而且,正如我在上一篇文章中提到的,这只是自定义分配器支持的开端。要支持 map 等其他集合类型,还有很多工作要做,有太多事情要完成。我认为我们目前拥有的东西已经足够有用,现在就可以开始使用它,也可以开始着手适配,并让库的使用者能够通过他们的 API 提供自己的分配器。
我很期待看到人们会构建出什么,以及它还能解锁哪些其他用例!