Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
Explain Struct Memory Alignment and CPU Padding in Go.
senior LevelCode ExamplegolangGo Language Core
In Simple Words: Modern 64-bit CPUs read memory in 8-byte word boundaries. If struct fields are not aligned to multiples of their size, the compiler inserts invisible padding bytes, increasing memory consumption.
To minimize memory footprint, order struct fields from largest to smallest:
go
// Bad: 24 bytes (1 + 7 pad + 8 + 1 + 7 pad)
type BadStruct struct {
a bool // 1 byte (+ 7 padding)
b int64 // 8 bytes
c bool // 1 byte (+ 7 padding)
}
// Optimized: 16 bytes (8 + 1 + 1 + 6 pad)
type GoodStruct struct {
b int64 // 8 bytes
a bool // 1 byte
c bool // 1 byte (+ 6 padding)
}