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.

Mar 7, 2025 - 05:32
 0

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.