Skip to content

Instantly share code, notes, and snippets.

@koron
Last active September 13, 2022 02:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koron/680bb3a74b20bf65b25a16b27472eefc to your computer and use it in GitHub Desktop.
Save koron/680bb3a74b20bf65b25a16b27472eefc to your computer and use it in GitHub Desktop.
deferが不要な時に使わないことによるメリットをベンチマーク
$ 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
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 }()
}
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)
}
}
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