Data alignment places values at addresses suitable for their type or hardware. Without it, a value can span two machine words and require two memory accesses; alignment can also introduce padding. section 12.4
Go guarantees alignment for these types:
- byte, uint8, and int8: 1 byte; uint16 and int16: 2 bytes. section 12.4
- uint32, int32, and float32: 4 bytes; uint64, int64, float64, and complex64: 8 bytes; complex128: 16 bytes. section 12.4
- Struct fields can create internal and trailing padding when their addresses must satisfy stricter alignment. section 12.4
Reordering fields reduces padding
type Foo struct { b1 byte; i int64; b2 byte } occupies 24 bytes because the int64 requires padding before it and the struct requires trailing padding. Reordering the fields as int64, byte, byte reduces the struct to 16 bytes. This matters when many values are stored in a slice: more relevant fields fit in each cache line. section 12.4
type Foo struct {
i int64
b1 byte
b2 byte
}
Inspect the compact field ordering that avoids the larger padding layout. section 12.4
