Created
April 10, 2015 16:31
-
-
Save phemmer/1d435f23c47dd1b22e62 to your computer and use it in GitHub Desktop.
defer vs no defer
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 ( | |
| "testing" | |
| ) | |
| type conn struct{} | |
| func (c *conn) Close() {} | |
| func (c *conn) Value() bool { | |
| return true | |
| } | |
| var v bool | |
| func benchmarkDefer() bool { | |
| conn := &conn{} | |
| defer conn.Close() | |
| return conn.Value() | |
| } | |
| func BenchmarkDefer(b *testing.B) { | |
| for n := 0; n < b.N; n++ { | |
| v = benchmarkDefer() | |
| } | |
| } | |
| func benchmarkNoDefer() bool { | |
| conn := &conn{} | |
| b := conn.Value() | |
| conn.Close() | |
| return b | |
| } | |
| func BenchmarkNoDefer(b *testing.B) { | |
| for n := 0; n < b.N; n++ { | |
| v = benchmarkNoDefer() | |
| } | |
| } |
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 test -v -bench=. | |
| testing: warning: no tests to run | |
| PASS | |
| BenchmarkDefer 10000000 110 ns/op | |
| BenchmarkNoDefer 1000000000 2.73 ns/op | |
| ok tmp/apr 4.272s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment