Memory-efficient enum arrays in Zig

# · 🔥 319 · 💬 237 · 10 months ago · alic.dev · dist1ll · 📷
Enums whose variants vary in size are prone to significant memory fragmentation in Rust. You could hand-roll specialized data structures for a particular enum that reduce fragmentation to a minimum; but doing this generically for an arbitrary enum with maximum memory efficiency is close to impossible in Rust. To me, one of the biggest motivators for efficient enum arrays has been compilers. A simple Vec(Expr) will consume sizeof(Enum) amount of memory for every element, which corresponds to the size of the largest variant + tag + padding. The most common way to improve packing efficiency is by just keeping the enum variants as small as possible using tagged indices. We get back a tagged index that holds both the enum tag and the index in the particular variant array. So as you can see, there's quite a few trade-offs we can make in this space - and they all depend on the concrete memory layout of our enum.
Memory-efficient enum arrays in Zig



Send Feedback | WebAssembly Version (beta)