Arena allocation in Zig
Five allocations, zero frees: the arena returns everything in one deinit.
const std = @import("std");
pub fn main() !void {
// An arena frees everything at once instead of piecemeal.
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = arena.allocator();
var total: usize = 0;
for (0..5) |i| {
const chunk = try alloc.alloc(u8, (i + 1) * 10);
total += chunk.len;
}
std.debug.print("five chunks, {d} bytes, one deinit\n", .{total});
}
How it works
ArenaAllocator.initwraps a backing allocator, here the page allocator.- The loop allocates five growing chunks and frees none of them.
defer arena.deinit()releases the lot at once — the arena's whole trade.
Keywords and builtins used here
constdeferfnforpubtryu8usizevarvoid
The run, in numbers
- Lines
- 15
- Characters to type
- 411
- Tokens
- 116
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 107 seconds.
Step 3 of 3 in Memory, step 21 of 27 in Language basics.