Skip to content

Instantly share code, notes, and snippets.

@vearutop
Created October 24, 2018 14:16
Show Gist options
  • Save vearutop/a468eeec07453eadaf73b14df806916e to your computer and use it in GitHub Desktop.
Save vearutop/a468eeec07453eadaf73b14df806916e to your computer and use it in GitHub Desktop.
early vs late referencing benchmark
package ref_test
import (
"testing"
)
type s struct {
ss string
}
func lateRef() *s {
i := s{ss: "sssss"}
i.ss = "bitch please"
return &i
}
func earlyRef() *s {
i := &s{ss: "sssss"}
i.ss = "bitch please"
return i
}
func noRef() s {
i := s{ss: "sssss"}
i.ss = "bitch please"
return i
}
func BenchmarkEarlyRef(b *testing.B) {
var i *s
b.ReportAllocs()
for n := 0; n < b.N; n++ {
i = earlyRef()
}
_ = i
}
func BenchmarkLateRef(b *testing.B) {
var i *s
b.ReportAllocs()
for n := 0; n < b.N; n++ {
i = lateRef()
}
_ = i
}
func BenchmarkNoRef(b *testing.B) {
var i s
b.ReportAllocs()
for n := 0; n < b.N; n++ {
i = noRef()
}
_ = i
}
goos: darwin
goarch: amd64
pkg: ref
BenchmarkEarlyRef-4 50000000 25.5 ns/op 16 B/op 1 allocs/op
BenchmarkLateRef-4 50000000 26.8 ns/op 16 B/op 1 allocs/op
BenchmarkNoRef-4 2000000000 0.32 ns/op 0 B/op 0 allocs/op
PASS
ok ref 3.372s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment