Created
January 9, 2018 16:14
-
-
Save fasterthanlime/8e30f53286edc67fbd17cc8ef00031d6 to your computer and use it in GitHub Desktop.
#golang for vs for-range benchmark
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 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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To run this: put
loops_test.go
in its own directory, and run: