Golang / Golang Internals and Memory Management Interview Questions
How does struct field ordering affect memory layout and performance in Go?
CPU architectures require data to be aligned — an 8-byte integer must start at an address divisible by 8, a 4-byte integer divisible by 4, etc. The Go compiler adds invisible padding bytes between struct fields to satisfy alignment requirements. Poor field ordering wastes memory; reordering fields can eliminate padding.
// Poorly ordered â wastes 7 bytes of padding type Wasteful struct { a bool // 1 byte // 7 bytes PADDING (for b's 8-byte alignment) b int64 // 8 bytes c bool // 1 byte // 7 bytes PADDING (to align next field / end of struct) } // Total: 24 bytes (wastes 14 bytes) // Well ordered â no padding (fields largest to smallest) type Compact struct { b int64 // 8 bytes a bool // 1 byte c bool // 1 byte // 6 bytes padding to align to 8-byte boundary at struct end } // Total: 16 bytes (saves 8 bytes vs Wasteful) // Verify with unsafe fmt.Println(unsafe.Sizeof(Wasteful{})) // 24 fmt.Println(unsafe.Sizeof(Compact{})) // 16 // Performance impact: // Larger structs â more cache lines â more cache misses in hot loops // A 50% size reduction can be a 2x performance improvement in array iteration // Tool: fieldalignment (golang.org/x/tools/go/analysis/passes/fieldalignment) // go install golang.org/x/tools/cmd/fieldalignment@latest // fieldalignment ./... â reports suboptimal struct layouts // fieldalignment -fix ./.. â rewrites structs (review before committing!) // go vet includes a similar check with: -structtag flag
The rule of thumb: order struct fields from largest to smallest alignment requirement. In practice: int64/float64/uintptr (8 bytes) first, then int32/float32 (4 bytes), then int16 (2 bytes), then bool/int8/byte (1 byte) last. This is particularly important for structs that appear in large arrays or slices processed in hot paths.
More Related questions...