Skip to content

Instantly share code, notes, and snippets.

@ii64
Created May 1, 2022 21:37
Show Gist options
  • Save ii64/4977808e7bb29e28a1b845d85b482c0b to your computer and use it in GitHub Desktop.
Save ii64/4977808e7bb29e28a1b845d85b482c0b to your computer and use it in GitHub Desktop.
package golang
import "testing"
var lookupMap = map[string]int{
"Constant": 1,
"Bool": 2,
"Byte": 3,
"I16": 4,
"I32": 5,
"I64": 6,
"Double": 7,
"String": 8,
"Binary": 9,
"Map": 10,
"List": 11,
"Set": 12,
"Enum": 13,
"Struct": 14,
"Union": 15,
"Exception": 16,
"Typedef": 17,
"Service": 18,
}
func lookupFunc1(s string) (int, bool) {
v, ok := lookupMap[s]
if !ok {
return 0, false
}
return v, true
}
func lookupFunc2(s string) (int, bool) {
switch s {
case "Constant":
return 1, true
case "Bool":
return 2, true
case "Byte":
return 3, true
case "I16":
return 4, true
case "I32":
return 5, true
case "I64":
return 6, true
case "Double":
return 7, true
case "String":
return 8, true
case "Binary":
return 9, true
case "Map":
return 10, true
case "List":
return 11, true
case "Set":
return 12, true
case "Enum":
return 13, true
case "Struct":
return 14, true
case "Union":
return 15, true
case "Exception":
return 16, true
case "Typedef":
return 17, true
case "Service":
return 18, true
}
return 0, false
}
var (
ks = []string{"Constant", "Bool", "Byte", "I16", "I32", "I64",
"Double", "String", "Map", "List", "Set", "Enum", "Struct", "Union", "Exception", "Typedef", "Service",
"Service", "Service", "Service", "Service", "Service", "Service", "Service", "Service", "Service", "Service", "Service", "Service",
}
)
func BenchmarkLookup1(b *testing.B) {
var (
rv int
re bool
)
for i := 0; i < b.N; i++ {
for _, k := range ks {
rv, re = lookupFunc1(k)
}
}
_, _ = rv, re
}
func BenchmarkLookup2(b *testing.B) {
var (
rv int
re bool
)
for i := 0; i < b.N; i++ {
for _, k := range ks {
rv, re = lookupFunc2(k)
}
}
_, _ = rv, re
}
// BenchmarkLookup1-12 7509818 157.3 ns/op 0 B/op 0 allocs/op
// BenchmarkLookup1-12 4537228 266.9 ns/op 0 B/op 0 allocs/op
// BenchmarkLookup2-12 13033747 90.41 ns/op 0 B/op 0 allocs/op
// BenchmarkLookup2-12 10001810 122.0 ns/op 0 B/op 0 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment