Created
July 13, 2015 18:03
-
-
Save vaskoz/50fc20c6346595c7a44e to your computer and use it in GitHub Desktop.
Defer significantly slower
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 ( | |
"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{}) | |
} |
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
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