Skip to content

Instantly share code, notes, and snippets.

@localhots
Created February 4, 2019 13:41
Show Gist options
  • Save localhots/299e8722fc487e35284d5c9f128ddffa to your computer and use it in GitHub Desktop.
Save localhots/299e8722fc487e35284d5c9f128ddffa to your computer and use it in GitHub Desktop.
Switch vs map performance in Go
$ go test -bench=.
goos: darwin
goarch: amd64
pkg: github.com/localhots/playground/switch_vs_map
BenchmarkSwitch-8 2000000000 0.34 ns/op
BenchmarkSwitchMiss-8 2000000000 0.64 ns/op
BenchmarkMap-8 300000000 4.11 ns/op
BenchmarkMapMiss-8 200000000 8.18 ns/op
PASS
ok github.com/localhots/playground/switch_vs_map 6.219s
package switchvsmap
func withSwitch(a int) bool {
switch a {
case 1, 2, 3:
return true
default:
return false
}
}
var m = map[int]struct{}{
1: struct{}{},
2: struct{}{},
3: struct{}{},
}
func withMap(a int) bool {
_, ok := m[a]
return ok
}
package switchvsmap
import "testing"
func BenchmarkSwitch(b *testing.B) {
for i := 0; i < b.N; i++ {
withSwitch(1)
}
}
func BenchmarkSwitchMiss(b *testing.B) {
for i := 0; i < b.N; i++ {
withSwitch(5)
}
}
func BenchmarkMap(b *testing.B) {
for i := 0; i < b.N; i++ {
withMap(1)
}
}
func BenchmarkMapMiss(b *testing.B) {
for i := 0; i < b.N; i++ {
withMap(5)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment