Skip to content

Instantly share code, notes, and snippets.

@robert-zaremba
Created January 27, 2021 16:20
Show Gist options
  • Save robert-zaremba/ea195543ec913186d80c305e84e38fac to your computer and use it in GitHub Desktop.
Save robert-zaremba/ea195543ec913186d80c305e84e38fac to your computer and use it in GitHub Desktop.
Go: benchmark len
package pkg
import "testing"
var a []int
var N = 200000000
func init() {
l := 10000
a = make([]int, l, l)
}
func BenchmarkLen1(b *testing.B) {
x := 0
for i := 0; i < N; i++ {
x += len(a)
}
println(x)
}
func BenchmarkLen2(b *testing.B) {
l := len(a)
x := 0
for i := 0; i < N; i++ {
x += l
}
println(x)
}
@robert-zaremba
Copy link
Author

robert-zaremba commented Jan 27, 2021

Result:

% go test -bench=.
2000000000000
goos: linux
goarch: amd64
BenchmarkLen1-4   	2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
1000000000	         0.108 ns/op
2000000000000
BenchmarkLen2-4   	2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000
2000000000000

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment