Skip to content

Instantly share code, notes, and snippets.

@brianfoshee
Created January 28, 2016 14:30
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 brianfoshee/f38d9238667a4474d4d9 to your computer and use it in GitHub Desktop.
Save brianfoshee/f38d9238667a4474d4d9 to your computer and use it in GitHub Desktop.
Benchmark finding a value in a slice
package loop
import "testing"
func BenchmarkFor(b *testing.B) {
for i := 0; i < b.N; i++ {
lang := "de-de"
supported := []string{"en-us", "ja-jp", "de-de"}
found := false
for _, s := range supported {
if lang == s {
found = true
}
}
if !found {
lang = "en-us"
}
}
}
func BenchmarkSwitch(b *testing.B) {
for i := 0; i < b.N; i++ {
lang := "de-de"
found := false
switch lang {
case "en-us", "ja-jp", "de-de":
found = true
}
if !found {
lang = "en-us"
}
}
}
func BenchmarkMap(b *testing.B) {
for i := 0; i < b.N; i++ {
lang := "de-de"
supported := map[string]interface{}{"en-us": nil, "ja-jp": nil, "de-de": nil}
_, found := supported[lang]
if !found {
lang = "en-us"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment