Skip to content

Instantly share code, notes, and snippets.

@dtjm
Last active April 18, 2016 16:34
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 dtjm/d232bf2ddb56d9e1349ca627450dba02 to your computer and use it in GitHub Desktop.
Save dtjm/d232bf2ddb56d9e1349ca627450dba02 to your computer and use it in GitHub Desktop.
Go map key optimization
package map_test
import (
"testing"
)
func BenchmarkMapStringKey(b *testing.B) {
var m map[string]string = make(map[string]string)
var k string = "key"
for i := 0; i < b.N; i++ {
_, _ = m[k]
}
}
func BenchmarkMapBytesKey(b *testing.B) {
var m map[string]string = make(map[string]string)
var k []byte = []byte("key")
for i := 0; i < b.N; i++ {
_, _ = m[string(k)]
}
}
func BenchmarkMapBytesConvertKey(b *testing.B) {
var m map[string]string = make(map[string]string)
var k []byte = []byte("key")
for i := 0; i < b.N; i++ {
var ks = string(k)
_, _ = m[ks]
}
}
$ go test -bench=. -benchmem map_test.go
testing: warning: no tests to run
PASS
BenchmarkMapStringKey-4 300000000 4.57 ns/op 0 B/op 0 allocs/op
BenchmarkMapBytesKey-4 200000000 7.00 ns/op 0 B/op 0 allocs/op
BenchmarkMapBytesConvertKey-4 100000000 20.8 ns/op 0 B/op 0 allocs/op
ok command-line-arguments 13.046s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment