$ go test -bench=.
goos: windows
goarch: amd64
pkg: gist.github.com/koron/bennchdefer
cpu: Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz
BenchmarkWithDefer-16 361817953 3.300 ns/op
BenchmarkWithoutDefer-16 1000000000 0.8443 ns/op
PASS
ok gist.github.com/koron/bennchdefer 2.650s
Last active
September 13, 2022 02:46
-
-
Save koron/680bb3a74b20bf65b25a16b27472eefc to your computer and use it in GitHub Desktop.
deferが不要な時に使わないことによるメリットをベンチマーク
This file contains 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 benchdefer | |
var withResult = 0 | |
func WithDefer(a, b int) { | |
withResult = 0 | |
defer func() { withResult *= b }() | |
withResult += a | |
} | |
var withoutResult = 0 | |
func WithoutDefer(a, b int) { | |
withoutResult = 0 | |
withoutResult += a | |
func() { withoutResult *= b }() | |
} |
This file contains 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 benchdefer | |
import "testing" | |
func run(a, b int) (int, int) { | |
WithDefer(a, b) | |
WithoutDefer(a, b) | |
return withResult, withoutResult | |
} | |
func TestBasic(t *testing.T) { | |
for i := 1; i < 1000; i++ { | |
for j := 1; j < 1000; j++ { | |
with, without := run(i, j) | |
if with != without { | |
t.Fatalf("unmatch results for %d,%d: with=%d without=%d", i, j, with, without) | |
} | |
} | |
} | |
} | |
func BenchmarkWithDefer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
WithDefer(i/1000, i%1000) | |
} | |
} | |
func BenchmarkWithoutDefer(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
WithoutDefer(i/1000, i%1000) | |
} | |
} |
This file contains 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
module gist.github.com/koron/bennchdefer | |
go 1.19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment