Skip to content

Instantly share code, notes, and snippets.

@nolash
Created June 4, 2018 09:57
Show Gist options
  • Save nolash/07907e493e06060251b71ea493f36522 to your computer and use it in GitHub Desktop.
Save nolash/07907e493e06060251b71ea493f36522 to your computer and use it in GitHub Desktop.
benchmark map versus array retrievals in go
package maparraybench
import (
"fmt"
"os"
"testing"
)
const (
itemCount = 100
)
func init() {
fmt.Fprintf(os.Stderr, "benchmark with %d items\n", itemCount)
}
func BenchmarkMap(b *testing.B) {
m := make(map[string]int)
for i := 0; i < itemCount; i++ {
m[fmt.Sprintf("%x", i)] = i
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for k, v := range m {
_ = k
_ = v
}
}
}
func BenchmarkArray(b *testing.B) {
var a []int
for i := 0; i < itemCount; i++ {
a = append(a, i)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j, v := range a {
_ = v
_ = j
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment