Created
January 28, 2016 14:30
-
-
Save brianfoshee/f38d9238667a4474d4d9 to your computer and use it in GitHub Desktop.
Benchmark finding a value in a slice
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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