Skip to content

Instantly share code, notes, and snippets.

@jordanschalm
Last active August 10, 2024 12:59
Show Gist options
  • Save jordanschalm/d4d268a39c6b2197a0c0882a4ca4dab5 to your computer and use it in GitHub Desktop.
Save jordanschalm/d4d268a39c6b2197a0c0882a4ca4dab5 to your computer and use it in GitHub Desktop.
Golang Defer Benchmark (1.22)
package bench
import (
"testing"
)
func doNoDefer(t *int) {
*t++
func() {
*t++
}()
}
func doDefer(t *int) {
defer func() {
*t++
}()
*t++
}
func BenchmarkDeferYes(b *testing.B) {
t := 0
for i := 0; i < b.N; i++ {
doDefer(&t)
}
}
func BenchmarkDeferNo(b *testing.B) {
t := 0
for i := 0; i < b.N; i++ {
doNoDefer(&t)
}
}
// Benchmark taken from https://medium.com/i0exception/runtime-overhead-of-using-defer-in-go-7140d5c40e32 which used an older Go version.
// I added one operation after the defer, to avoid compiler optimizations that wouldn't appear in typical code.
// On Go 1.22 in this modified benchmark, defer costs about 100% or 2ns.
//
// % go version
// go version go1.22.4 darwin/arm64
//
// % go test -bench=.
// goos: darwin
// goarch: arm64
// pkg: local/scratch/bench
// BenchmarkDeferYes-10 279516777 4.237 ns/op
// BenchmarkDeferNo-10 532519959 2.246 ns/op
// PASS
// ok local/scratch/bench 3.505s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment