Skip to content

Instantly share code, notes, and snippets.

@buarki
Created April 27, 2025 15:23
Show Gist options
  • Select an option

  • Save buarki/27824ef45d47e2a39795a9d8cfff9bb9 to your computer and use it in GitHub Desktop.

Select an option

Save buarki/27824ef45d47e2a39795a9d8cfff9bb9 to your computer and use it in GitHub Desktop.
Struct layout article
package main
import (
"unsafe"
)
// Poor layout - fields ordered by size
type PoorLayout struct {
a bool // 1 byte
b int64 // 8 bytes
c bool // 1 byte
d int32 // 4 bytes
e bool // 1 byte
}
// Optimized layout - larger fields first
type OptimizedLayout struct {
b int64 // 8 bytes
d int32 // 4 bytes
a bool // 1 byte
c bool // 1 byte
e bool // 1 byte
}
func main() {
// Print struct sizes
println("PoorLayout size:", unsafe.Sizeof(PoorLayout{}), "bytes")
println("OptimizedLayout size:", unsafe.Sizeof(OptimizedLayout{}), "bytes")
}
package main
import "testing"
// Benchmark to measure memory allocation
func BenchmarkMemoryAllocation(b *testing.B) {
b.Run("PoorLayout", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = make([]PoorLayout, 1000000)
}
})
b.Run("OptimizedLayout", func(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = make([]OptimizedLayout, 1000000)
}
})
}
// Benchmark to measure access time
func BenchmarkFieldAccess(b *testing.B) {
poor := make([]PoorLayout, 1000000)
optimized := make([]OptimizedLayout, 1000000)
b.Run("PoorLayout", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for j := range poor {
poor[j].b = int64(j)
}
}
})
b.Run("OptimizedLayout", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for j := range optimized {
optimized[j].b = int64(j)
}
}
})
}
@buarki
Copy link
Author

buarki commented Apr 27, 2025

To get outputs:

go test -bench=. -benchmem

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment