go / expert
Snippet
Optimizing Struct Memory Alignment
Go aligns struct fields based on their size. Large fields should come first to minimize padding bytes added by the compiler to ensure memory address alignment.
snippet.go
1
2
3
4
5
6
7
8
9
10
11
type Optimized struct {A int64 // 8 bytesB int32 // 4 bytesC bool // 1 byte} // Total: 16 bytes (3 bytes padding)type Unoptimized struct {C bool // 1 byteA int64 // 8 bytes (7 bytes padding!)B int32 // 4 bytes} // Total: 24 bytes
Breakdown
1
A int64 // 8 bytes
Placing the largest field first prevents unnecessary gaps.
2
C bool // 1 byte
The compiler adds 7 bytes of padding after this in the unoptimized version to align the next int64.