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
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
Practical Exercise
When It Matters
- Millions of structs in memory (caches, databases)
- CPU cache efficiency (cache line = 64 bytes)
- Network protocols with fixed layouts