Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dolanor
Created January 2, 2018 15:05
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 dolanor/42742f8a5d834df3a2fb8d77c44c1d68 to your computer and use it in GitHub Desktop.
Save dolanor/42742f8a5d834df3a2fb8d77c44c1d68 to your computer and use it in GitHub Desktop.
Check speed of iterating with an index or the ranged value
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