Skip to content

Instantly share code, notes, and snippets.

@vaskoz
Created July 13, 2015 18:03
Show Gist options
  • Save vaskoz/50fc20c6346595c7a44e to your computer and use it in GitHub Desktop.
Save vaskoz/50fc20c6346595c7a44e to your computer and use it in GitHub Desktop.
Defer significantly slower
package main
import (
"flag"
"log"
"runtime"
"sync"
"testing"
)
func deferBench(b *testing.B) {
lock := sync.Mutex{}
for i := 0; i < b.N; i++ {
func() {
lock.Lock()
defer lock.Unlock()
}()
}
}
func noDeferBench(b *testing.B) {
lock := sync.Mutex{}
for i := 0; i < b.N; i++ {
func() {
lock.Lock()
lock.Unlock()
}()
}
}
func main() {
log.Println(runtime.Version())
flag.Set("test.bench", "foo")
flag.Set("test.v", "true")
testing.Main(func(pat, str string) (bool, error) { return true, nil },
[]testing.InternalTest{},
[]testing.InternalBenchmark{{"defer benchmark", deferBench}, {"no defer bench", noDeferBench}},
[]testing.InternalExample{})
}
go run defer_bench.go
2015/07/13 12:02:44 devel +ca6ba49 Mon Jul 13 06:40:00 2015 +0000
testing: warning: no tests to run
PASS
defer benchmark-8 20000000 98.8 ns/op
no defer bench-8 100000000 21.8 ns/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment