Skip to content

Instantly share code, notes, and snippets.

@fasterthanlime
Created January 9, 2018 16:14
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 fasterthanlime/8e30f53286edc67fbd17cc8ef00031d6 to your computer and use it in GitHub Desktop.
Save fasterthanlime/8e30f53286edc67fbd17cc8ef00031d6 to your computer and use it in GitHub Desktop.
#golang for vs for-range benchmark
package loops_test
import (
"testing"
)
var totalPkg byte
func BenchmarkForRangeArray(b *testing.B) {
var arr [128 * 1024]byte
var total byte
for n := 0; n < b.N; n++ {
for _, v := range arr {
total += v
}
}
totalPkg = total
}
func BenchmarkForRangeSlice(b *testing.B) {
var arr [128 * 1024]byte
var total byte
for n := 0; n < b.N; n++ {
for _, v := range arr[:] {
total += v
}
}
totalPkg = total
}
func BenchmarkClassicFor(b *testing.B) {
var arr [128 * 1024]byte
var total byte
for n := 0; n < b.N; n++ {
for i := 0; i < len(arr); i++ {
total += arr[i]
}
}
totalPkg = total
}
@fasterthanlime
Copy link
Author

To run this: put loops_test.go in its own directory, and run:

go test -bench .

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