Problem Statement
At a high-frequency trading firm, every byte matters. A poorly aligned struct wastes 40% memory. Explain struct alignment and optimize a given struct layout.
The Problem: Padding Waste
// BAD: 24 bytes due to padding
type BadStruct struct {
a bool // 1 byte + 7 padding
b int64 // 8 bytes
c bool // 1 byte + 7 padding
}
// GOOD: 16 bytes (reordered)
type GoodStruct struct {
b int64 // 8 bytes
a bool // 1 byte
c bool // 1 byte + 6 padding
}Alignment Rules
| Type | Size | Alignment |
|---|---|---|
| bool, int8, uint8 | 1 byte | 1 byte |
| int16, uint16 | 2 bytes | 2 bytes |
| int32, uint32, float32 | 4 bytes | 4 bytes |
| int64, uint64, float64, pointer | 8 bytes | 8 bytes |
Use fieldalignment Tool
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
fieldalignment -fix ./...
# Output:
# struct of size 24 could be 16Practical Exercise
// Optimize this struct:
type User struct {
IsActive bool // 1
Age int32 // 4
ID int64 // 8
IsVerified bool // 1
Score float64 // 8
Flags uint8 // 1
}
// Before: 40 bytes
// After optimization: 32 bytes
type UserOptimized struct {
ID int64 // 8
Score float64 // 8
Age int32 // 4
IsActive bool // 1
IsVerified bool // 1
Flags uint8 // 1 + 1 padding
}When It Matters
- Millions of structs in memory (caches, databases)
- CPU cache efficiency (cache line = 64 bytes)
- Network protocols with fixed layouts