Memory Layout
In Go, structs are stored in memory as a contiguous block. The fields are placed one after another in the order they are defined.
Alignment and Padding
Go aligns fields to specific memory boundaries to improve execution speed. If a small field is followed by a larger one, Go may add padding (wasted space) to align the next field correctly.
type stats struct {
NumPosts uint8 // 1 byte
// 1 byte padding here
Reach uint16 // 2 bytes
NumLikes uint8 // 1 byte
// 1 byte padding here
}
Optimization
To minimize memory usage, you can order your fields from largest to smallest. This reduces the amount of padding required by the compiler.
type optimizedStats struct {
Reach uint16 // 2 bytes
NumPosts uint8 // 1 byte
NumLikes uint8 // 1 byte
}
While you shouldn’t obsess over this for small applications, it can save significant memory (gigabytes) in high-performance systems with millions of struct instances.