I was recently encouraged to watch A Practical Guide to Applying Data Oriented Design (DoD) by Andrew Kelley, the creator of Zig. Just 10 minutes into the talk, I was confronted with a skill I had never formally learned… the arithmetic behind memory layout of types. Throughout the talk, Andrew tested the audience’s ability to compute the alignment and sizes of various types, starting with primitives like u32 and bool, and ending with some more complex structures involving enums, unions, and more. As far as I can tell, the exact rules for computing the alignment and size of a type in Zig are not made explicit in any documentation, but are understood by those in-the-know. As a late-comer to low-level programming myself, I thought I’d collect here some formulas & explanations I landed on while wrestling with alignment and sizing in Zig. Memory Layout Principles For any piece of data stored in memory on a computer, the data must have some natural alignment and size dimensions according to its type. Intuitively, its size captures how many bytes it would take to specify the information that should be contained in any instance of that type. Whereas, its alignment captures the spacing the compiler must obey when choosing valid addresses at which to place data of this type. I imagine just about any computer science major would have learned the rules of memory layout according to some kind of C-like compiler. I guess the motivation would go something like: “CPUs fetch data from memory in fixed-size blocks of so-many bytes, and performance degrades when data is misaligned. So, compilers automatically pad and align data types.” In particular, types that don’t “fill up” all of the space in memory allocated to them will be padded with extra bits/bytes to make up for the difference. Andrew’s whole message in his DoD talk centered on designing your data types to take up as little space in memory as possible, which includes reducing the size, alignment, and padding required to repre...
First seen: 2026-01-24 20:52
Last seen: 2026-01-24 21:52