Skip to content

Instantly share code, notes, and snippets.

@collinvandyck
Created January 29, 2014 00:32
Show Gist options
  • Select an option

  • Save collinvandyck/8679407 to your computer and use it in GitHub Desktop.

Select an option

Save collinvandyck/8679407 to your computer and use it in GitHub Desktop.
damn reflect you slow but i still <3 you
package main
import (
"reflect"
"testing"
)
func BenchmarkMapsEqualsManual(b *testing.B) {
m1 := newMap()
m2 := newMap()
for i := 0; i < b.N; i++ {
manualEquals(m1, m2)
}
}
func BenchmarkMapsEqualReflection(b *testing.B) {
m1 := newMap()
m2 := newMap()
for i := 0; i < b.N; i++ {
reflect.DeepEqual(m1, m2)
}
}
func manualEquals(m1, m2 map[string]string) bool {
if len(m1) != len(m2) {
return false
}
for k,v := range m1 {
if v2, ok := m2[k]; !ok || v != v2 {
return false
}
}
return true
}
func newMap() map[string]string {
m := make(map[string]string)
m["foo"] = "bar"
m["bar"] = "baz"
return m
}
~/Desktop % go test -bench .
testing: warning: no tests to run
PASS
BenchmarkMapsEqualsManual 20000000 86.0 ns/op
BenchmarkMapsEqualReflection 2000000 958 ns/op
ok _/Users/cvandyck/Desktop 4.671s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment