Skip to content

Instantly share code, notes, and snippets.

@kumatch
Created August 6, 2018 08:23
Show Gist options
  • Save kumatch/2cf151d82251a1ff5dd796bceb58bbcb to your computer and use it in GitHub Desktop.
Save kumatch/2cf151d82251a1ff5dd796bceb58bbcb to your computer and use it in GitHub Desktop.
go map access
# go test -bench . -benchmem
goos: darwin
goarch: amd64
BenchmarkMap1-4 100000 24314 ns/op 2800 B/op 280 allocs/op
BenchmarkMap2-4 50000 25083 ns/op 2800 B/op 280 allocs/op
package main
import (
"testing"
"fmt"
)
func createItems(prefix string, num int) []string {
items := make([]string, num)
for i := 0; i < num; i++ {
items[i] = fmt.Sprintf("%s_%04d", prefix, i)
}
return items
}
func BenchmarkMap1(b *testing.B) {
mains := createItems("main", 1000)
subs := createItems("sub", 1000)
var total int
maps := make(map[string]map[string]int)
for _, main := range mains {
maps[main] = make(map[string]int)
for _, sub := range subs {
total++
maps[main][sub] = total
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 10; j < 80; j++ {
mkey := fmt.Sprintf("main_%04d", j)
skey := fmt.Sprintf("sub_%04d", j)
if _, ok := maps[mkey][skey]; !ok {
b.Errorf("map1 error: main = %s, sub = %s", mkey, skey)
}
}
}
}
func BenchmarkMap2(b *testing.B) {
mains := createItems("main", 1000)
subs := createItems("sub", 1000)
var total int
maps := make(map[string]int)
for _, main := range mains {
for _, sub := range subs {
total++
key := main + "_" + sub
maps[key] = total
}
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for j := 10; j < 80; j++ {
mkey := fmt.Sprintf("main_%04d", j)
skey := fmt.Sprintf("sub_%04d", j)
if _, ok := maps[mkey + "_" + skey]; !ok {
b.Errorf("map2 error: main = %s, sub = %s", mkey, skey)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment