Consider this benchmark, where we compare map access vs switch
var code = []int32{0, 10, 100, 100, 0, 10, 0, 10, 100, 14, 1000, 100, 1000, 0, 0, 10, 100, 1000, 10, 0, 1000, 12}
var mapCode = map[int32]int32{
0: 1,
10: 2,
100: 3,
1000: 4,
}
func BenchmarkMap(b *testing.B) {
success := int32(0)
fail := int32(0)
for n := 0; n < b.N; n++ {
// for each value in code array, do a specific action
for _, v := range code {
c, ok := mapCode[v]
if !ok {
fail++
} else {
success += c
}
}
}
}
func BenchmarkSwitch(b *testing.B) {
success := int32(0)
fail := int32(0)
for n := 0; n < b.N; n++ {
// for each value in code array, do a specific action
for _, v := range code {
switch v {
case 0:
success++
case 10:
success += 2
case 100:
success += 3
case 1000:
success += 4
default:
fail++
}
}
}
}
Here is the results:
BenchmarkMap-2 5000000 277 ns/op 0 B/op 0 allocs/op
BenchmarkSwitch-2 30000000 48.2 ns/op 0 B/op 0 allocs/op
So using map seems to be way slower than switch.
I'm currently trying to optimize a function using a code similar to BenchmarkMap()
, where the map access
is the bottleneck, but I can't use switch as the map is dynamically generated when the program start (ie it
may change according to input arguments)
Is there a way to get similar performance as switch x {}
with dynamically generated map ?
sort.Search
which is a generalized tool to search in sorted slices using binary search algorythm. – Skell