💻 Tech
The Go compiler creates padding and alignment in structs to enhance performance and memory efficiency. This is an internal mechanism by the compiler, and it’s recommended not to rearrange your struct members unless absolutely necessary. The focus should be on the logical order of the members according to the context of the Go program.
A word is a unit of data that defines the length a processor can handle in one operation. The value of the word depends on the architecture:
- 16-bit arch: 2 bytes
- 32-bit arch: 4 bytes
- 64-bit arch: 8 bytes
Go uses alignment (the largest word depending on the data type) and padding (the number of unused bytes needed to meet the alignment requirements).
In the example below, the alignment is 4 bytes because it includes an int32.
- 3 bytes are padded after A, so it’ll total to 4 bytes (1 byte came from A).
- 2 bytes are padded after C, so it’ll total to 4 bytes (2 bytes came from C).
In total, we have 12 bytes. With this, each processor operation can safely perform based on the alignment size without losing data or requiring extra operations. Note that padding is performed by the compiler during compilation; this is not added in the code.
type Example struct {
A byte
_ [3]byte // padding
B int32
C int16
_ [2]byte // padding
}
However, the number of bytes added can be reduced. Note that this should not be performed unless absolutely necessary.
The modified code below arranges the struct in descending order based on the number of bytes. With this, the compiler only needs to pad 1 byte. The total bytes allocated to the struct is 8 bytes as opposed to 12 bytes in the previous version of the code.
type Example struct {
B int32
C int16
A byte
_ [1]byte // padding
}