Skip to content

Instantly share code, notes, and snippets.

@kolyshkin
Created February 7, 2025 21:18
Show Gist options
  • Save kolyshkin/98ff9ff8de39e3e548bc84808e3d10b8 to your computer and use it in GitHub Desktop.
Save kolyshkin/98ff9ff8de39e3e548bc84808e3d10b8 to your computer and use it in GitHub Desktop.
package main
import "testing"
// Original version that returns by value
type Thing struct {
c *Config
}
func (t *Thing) Config() Config {
return *t.c
}
type Config struct {
name string
foo [10]int
bar [20]int
}
func (c Config) Foo(i int) int {
return c.foo[i]
}
func (c Config) Bar(i int) int {
return c.bar[i]
}
func newThing() Thing {
return Thing{
c: &Config{
name: "woohoo",
foo: [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10},
bar: [20]int{33, 34, 35},
},
}
}
func BenchmarkConfigByValue(b *testing.B) {
t := newThing()
var a, x int
b.ResetTimer()
for i := 0; i < b.N; i++ {
a = t.Config().Foo(1)
x = t.Config().Bar(2)
}
// Use the variables to prevent optimizer from eliminating the code
_ = a
_ = x
}
func BenchmarkConfigByPointer(b *testing.B) {
t := newThing()
var a, x int
b.ResetTimer()
for i := 0; i < b.N; i++ {
a = t.c.Foo(1)
x = t.c.Bar(2)
}
// Use the variables to prevent optimizer from eliminating the code
_ = a
_ = x
}
func BenchmarkConfigByValueWithLocal(b *testing.B) {
t := newThing()
var a, x int
b.ResetTimer()
for i := 0; i < b.N; i++ {
// Store config in local variable to avoid double copy
c := t.Config()
a = c.Foo(1)
x = c.Bar(2)
}
// Use the variables to prevent optimizer from eliminating the code
_ = a
_ = x
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment