Created
January 2, 2018 15:05
-
-
Save dolanor/42742f8a5d834df3a2fb8d77c44c1d68 to your computer and use it in GitHub Desktop.
Check speed of iterating with an index or the ranged value
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 main_test | |
import ( | |
"testing" | |
) | |
type Whatever struct { | |
a, b, c int | |
} | |
func BenchmarkSliceRangeIteration(b *testing.B) { | |
s := []Whatever{ | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for _, v := range s { | |
a, b, c := v.a, v.b, v.c | |
_, _, _ = a, b, c | |
} | |
} | |
} | |
func BenchmarkSliceIndexIteration(b *testing.B) { | |
s := []Whatever{ | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
Whatever{1, 2, 3}, | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
for i := range s { | |
a, b, c := s[i].a, s[i].b, s[i].c | |
_, _, _ = a, b, c | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment