
Understanding Struct Field Alignment in Go
Ahnii! When working with Go structs, the way fields are ordered can significantly impact memory usage. Let's explore how struct field alignment works and how to optimize it. The Basics of Memory Alignment // Bad alignment (72 bytes total) type BadStruct struct { name string // 16 bytes (string header: ptr + len) enabled bool // 1 byte + 7 bytes padding items [] int // 24 bytes (slice header: ptr + len + cap) config * Config // 8 bytes (pointer) } Here the enabled bool field (1 byte) sits between two 8-byte-aligned fields, so the compiler inserts 7 bytes of padding after it, inflating the struct to 72 bytes. Memory Sizes in Go bool: 1 byte int/uint: 8 bytes on 64-bit systems pointer: 8 bytes on 64-bit systems string: 16 bytes (two 8-byte words) slice: 24 bytes (three 8-byte words) interface: 16 bytes (two 8-byte words) Optimizing Field Order // Good alignment (40 bytes total) type GoodStruct struct { items [] int // 24 bytes (largest first) name string // 16 bytes config * Config // 8 b
Continue reading on Dev.to
Opens in a new tab



