Did you know that the way you order fields in a Go struct can waste memory? Go automatically adds padding bytes to ensure proper memory alignment, and a poorly structured layout can increase memory usage by 30% or more!
β Bad Struct: Wasting Memory
type BadStruct struct {
A int8 // 1 byte
B int64 // 8 bytes
C int8 // 1 byte
}
Checking its size:
fmt.Println(unsafe.Sizeof(BadStruct{})) // Output: 24 bytes
Even though the actual data is just 10 bytes, the struct takes up 24 bytes due to padding.
π Step-by-step memory layout (BadStruct)
Field | Type | Size (bytes) | Offset | Why? |
---|---|---|---|---|
A |
int8 | 1 | 0 | Starts at 0, perfectly aligned |
(padding) | - | 7 | 1-7 | Added to align B to the next 8-byte boundary |
B |
int64 | 8 | 8 | Must start at an 8-byte-aligned address |
C |
int8 | 1 | 16 | Starts at the next available byte |
(padding) | - | 7 | 17-23 | Ensures struct size is a multiple of 8 |
Total size:
1 (A) + 7 (padding) + 8 (B) + 1 (C) + 7 (padding) = 24 bytes
π Go adds 14 bytes of padding, making the struct much larger than necessary! π±
β Optimized Struct: Efficient Memory Use
type GoodStruct struct {
B int64 // 8 bytes
A int8 // 1 byte
C int8 // 1 byte
}
Checking its size:
fmt.Println(unsafe.Sizeof(GoodStruct{})) // Output: 16 bytes
By simply reordering fields, we reduce the struct size by 33% (from 24B to 16B)! π
π Step-by-step memory layout (GoodStruct)
Field | Type | Size (bytes) | Offset | Why? |
---|---|---|---|---|
B |
int64 | 8 | 0 | Starts at 0, perfectly aligned |
A |
int8 | 1 | 8 | Starts immediately after B
|
C |
int8 | 1 | 9 | Starts right after A
|
(padding) | - | 6 | 10-15 | Ensures struct size is a multiple of 8 |
Total size:
8 (B) + 1 (A) + 1 (C) + 6 (padding) = 16 bytes
π By placing larger fields first, we eliminate unnecessary padding and optimize memory usage!
π Why Does This Happen?
Go aligns fields based on their natural size (e.g., int64
must be at an address divisible by 8).
- If a smaller field (
int8
) comes before a larger field (int64
), Go inserts padding bytes to align memory correctly. - By placing larger fields first, we reduce unnecessary padding, making the struct smaller and more efficient.
π Pro Tip
Use this to check field memory offsets:
reflect.TypeOf(struct{}).Field(i).Offset
π¬ Have you optimized struct layouts in your Go projects? Let's discuss in the comments! π
#Golang #MemoryOptimization #Performance #GoLangTips #SoftwareEngineering
Top comments (0)