The State of Allocators in 2026 - Finally Stabilised

本文为原文前 6,000 字符的节选翻译,完整内容请查看原文。

The State of Allocators in 2026 - Finally Stabilised

It’s only been a couple of months since the last article, and I am pleased to see that, after 10 years of limbo, allocators have finally been stabilised! While it feels like the never type did steal a bit of thunder, rust 1.100 was nonetheless a monumental release. Congratulations on the team that shepherded this through. So, now we have an MVP of the allocator API, what can we do with it? What does it get us besides closer feature parity with other system languages like C++ & Zig? In this article I’ll step through a few use cases that might be handy to the layman rust programmer, so hopefully you can see the benefit.

距离上一篇文章才过去几个月,我很高兴地看到,在经历了 10 年的悬而未决之后,分配器终于稳定下来了!虽然感觉 never 类型抢走了一些风头,但 Rust 1.100 仍然是一个里程碑式的版本。祝贺引导这一进程的团队。那么,现在我们有了分配器 API 的最小可行性产品(MVP),我们能用它做什么呢?除了在功能上更接近 C++ 和 Zig 等其他系统语言之外,它还能给我们带来什么?在本文中,我将介绍几个对普通 Rust 程序员可能很有用的用例,希望你能从中看到它的好处。

Allocators can adjust when memory is freed This was one of the leading cases for custom allocation. Dropping in rust is not free. There has been prior art in actually moving memory to a dedicated thread to Drop highly nested structures. This is actually only half a solution. You’re still paying for the deallocation call costs, just it’s not in the hot path anymore. Instead, what if we knew that we would have a period of time in our code, where we’re going to allocate a lot of stuff, do something with it, and then free everything? A good example of this is a web request, or a database query. A request comes in, fills in some data structures, and then when the request finishes, the memory isn’t needed anymore so it’s dropped.

分配器可以调整内存释放的时间。这是自定义分配的主要用例之一。在 Rust 中,Drop 并非免费。此前已有将内存移动到专用线程来 Drop 高度嵌套结构的先例。但这实际上只解决了一半的问题。你仍然需要支付反分配(deallocation)调用的成本,只是它不再处于关键路径(hot path)上了。相反,如果我们知道代码中有一段时间会分配大量内容,处理完后再释放所有内容,会怎样呢?Web 请求或数据库查询就是一个很好的例子。一个请求进来,填充一些数据结构,当请求结束时,内存就不再需要了,于是被释放。

This sort of “burst” pattern of allocation, where you allocate a lot up front, and then tear things down all at once at the end, is quite common. For this we can use a bump allocator: reserve a big block of memory, and allocate from that, rather than paying the cost of talking to the system allocator for every allocation. Think of it like the BufReader and BufWriter of std io, rather than make repeated syscalls to fetch data, we can buffer that data in a big block, so that we can reduce the overhead considerably. You want more memory? Just check if the size fits in our block, return that slice, increment our counter (bump!), and we’re done. We can add more blocks as well, if we run out. This makes allocations very cheap, we don’t need to keep much state around besides from a counter.

这种“突发式”分配模式——即预先分配大量内存,最后一次性销毁——非常常见。为此,我们可以使用碰撞分配器(bump allocator):预留一大块内存,并从中进行分配,而不是为每次分配都支付与系统分配器交互的成本。可以把它想象成 std io 中的 BufReader 和 BufWriter,与其反复进行系统调用来获取数据,不如将数据缓冲在一个大块中,从而显著降低开销。需要更多内存?只需检查大小是否适合我们的块,返回该切片,增加计数器(碰撞!),就完成了。如果内存用完了,我们还可以添加更多的块。这使得分配变得非常廉价,除了一个计数器外,我们不需要维护太多的状态。

The downsides of this approach is when we come to deallocate memory. We don’t keep track around where individual allocations are made. However, this actually solves our drop takes a long time problem, since we can just deallocate everything all at once. Essentially if the impl of the bump allocator is: 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, // how much of it we’ve handed out used: Cell, } impl Bump { fn new() -> Self { let data = Global.allocate(LAYOUT).expect(“out of memory”).cast::(); 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, _layout: Layout) { // deliberately a no-op! } }

这种方法的缺点在于反分配内存时。我们不会追踪单个分配是在哪里进行的。然而,这实际上解决了“drop 耗时过长”的问题,因为我们可以一次性反分配所有内容。本质上,如果碰撞分配器的实现如下:[代码略]。

Then we can use it like so: 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); There are a few tradeoffs for doing things like this in a bump allocator, and not every allocation is going to benefit. Hence why it’s important to be able to adjust our allocation strategy locally rather than just globally. However, an astute reader might notice that, if we are bumping large swathes of memory, this is going to possibly cause our memory usage to increase considerably. Well, that brings us to our next section: memory accounting.

然后我们可以这样使用它:[代码略]。在碰撞分配器中这样做有一些权衡,并非每次分配都能从中受益。因此,能够局部而非全局地调整分配策略非常重要。然而,敏锐的读者可能会注意到,如果我们碰撞(分配)大片内存,这可能会导致内存使用量大幅增加。好吧,这就引出了我们的下一节:内存核算。

Allocators can let us know how much memory they’re using The next challenge that can be solved by custom allocators is knowing how much memory particular sections of code is being used. I.e, memory accounting. The key here is that, we can use existing allocators, and sprinkle in some extra bookkeeping to keep a pretty accurate ledger. There are a number of use cases that accounting can shape the behaviour of code. Say you have a cache of objects, and you want to set a threshold above which, we start evicting entries. Or say you want to do an external sort, but you don’t know how big your data structures are at the start, but you want to use up as much memory as possible. Or maybe you are wanting to place a limit on a code sandbox, because it’s sharing resources with other sandboxes. What you can do is wrap an allocator, with a custom accounting layer, and use this to drive your decisions. I.e, here is a very trivial example: struct AccountedAllocator<A: Allocator> { inner: A, allocated: AtomicUsize, } impl<A: Allocator> AccountedAllocator { 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 { fn allocate(&self, layout: Layout)

分配器可以让我们知道它们正在使用多少内存。自定义分配器可以解决的下一个挑战是了解代码的特定部分正在使用多少内存。即内存核算。这里的关键在于,我们可以使用现有的分配器,并加入一些额外的簿记工作来保持一个相当准确的账本。有许多用例可以通过核算来改变代码的行为。假设你有一个对象缓存,并且你想设置一个阈值,超过该阈值就开始驱逐条目。或者假设你想进行外部排序,但一开始不知道数据结构有多大,却想尽可能多地使用内存。或者,你可能想对代码沙箱进行限制,因为它与其他沙箱共享资源。你可以做的是用一个自定义的核算层包装一个分配器,并用它来驱动你的决策。即,这是一个非常简单的例子:[代码略]。