Organizing Structs for Memory Efficiency

Go is generally a very memory efficient language to work in, but knowing this little technique can make it that bit more efficient again.

First, we’ll look at structs - they are a composite data type used to group together zero or more values, each with its own name and type, under a single name. They are the foundation for building complex data structures and objects.

Memory alignment is an essential aspect to consider when organizing structs in Go. The padding introduced due to alignment can lead to memory waste. To reduce padding and optimize memory usage, follow these guidelines:

  • Order fields by size: Arrange struct fields from largest to smallest types, grouping fields with the same size together.
  • Use types with smaller memory footprints: Use smaller data types, such as int32 instead of int64, if possible, to save memory.

Example:

1
2
3
4
5
6
type InefficientStruct struct {
    a bool    // 1 byte
    b int64   // 8 bytes
    c bool    // 1 byte
    d float32 // 4 bytes
}
1
2
3
4
5
6
type EfficientStruct struct {
    b int64   // 8 bytes
    d float32 // 4 bytes
    a bool    // 1 byte
    c bool    // 1 byte
}

You can see from the examples above, shifting the bool variables in the struct to the end means the compiler won’t have to add padding to them, like it would have to in InefficientStruct.

In conclusion, organizing structs in Go for better memory efficiency can lead to improved application performance and reduced resource consumption.