Senior
What is struct alignment in Go? How to optimize struct fields for memory?
sobes.tech AI
Answer from AI
In Go, struct alignment is related to how the compiler arranges fields in memory to ensure efficient access by the processor. Each struct field is aligned to a boundary that is a multiple of its type's size (for example, 4 bytes for int32). If fields are not optimally ordered, padding bytes may be inserted between them, increasing the overall size of the struct.
To optimize memory layout, fields should be ordered from largest to smallest. This minimizes the amount of padding inserted.
Example:
// Not optimal
struct1 := struct {
a byte // 1 byte
b int64 // 8 bytes
}{}
// Optimal
struct2 := struct {
b int64 // 8 bytes
a byte // 1 byte
}{}
In the first case, 7 bytes of padding will be added between a and b, while in the second case, the struct will occupy less memory.
You can also use tools like go tool compile -m to see warnings about inefficient alignment.