Created
April 27, 2025 15:23
-
-
Save buarki/27824ef45d47e2a39795a9d8cfff9bb9 to your computer and use it in GitHub Desktop.
Struct layout article
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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") | |
| } | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } | |
| }) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To get outputs:
go test -bench=. -benchmem