Initial ArenaAllocator node capacity

Hello!

One of the things I like about arenas is essentially the dynamic array you get for free assuming your arena is big enough, and allows you to grow an element at a time. But I suspect std.heap.ArenaAllocator may not be great for this.

From what I gathered by looking at alloc’s source code, it seems the starting arena node will only have 16 bytes, and new nodes will only be larger by however much more memory I need + 16 bytes at a time. This makes it worse than a GPA for dynamic arrays, as it will cause essentially just as many re-allocations, but without de-allocating the previous version of the array. It would also make the “grow at every insert” approach massively inefficient.

The snippet that made me think this was the case:

fn alloc(ctx: *anyopaque, n: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 {
        // ...
        const new_node: *Node = new_node: {
            // ...

            // prev size here is 0, in the first allocation
            const size: Node.Size = size: {
                const min_size = @sizeOf(Node) + alignment.toByteUnits() + n;
                const big_enough_size = prev_size + min_size + 16;
                const size = mem.alignForward(usize, big_enough_size + big_enough_size / 2, 2);
                break :size .fromInt(size);
            };
            // ...
        }
        // ...
}

Is there a way to specify some base size for the first allocated node, or is there a better approach?

You can explicitly grow the arena when creating by using alloc(u8, 4096); free

I agree that it should come in the std.

slightly optimized version of the above: zml/stdx/stdx.zig at 8fcff8c462070d06056f8a85ba0c8a81f0f3a636 · zml/zml · GitHub

Note that this isn’t entirely correct. Note thebig_enough_size + big_enough_size / 2 part that is in the snippet you posted. This essentially, with the lines above, does the exponential growth like a dynamic array.

Oh true. idk how I missed that hahah

Btw, out of curiosity: do you know why the +16 specifically? Is it just so single-byte allocations aren’t as innefficient? It seems kind of arbitrary, and also low.

Thank you both!

Yes, likely this and also such that the exponential growth has a higher starting point, such that there aren’t as many nodes.