Open
Description
In programming, sometimes it is less verbose by using a map with bool key than using an if-else block. For example:
if condition {
counter++
} else {
counter--
}
vs.
var boolToInt = map[bool]int{true: 1, false: 0}
...
counter += boolToInt[condition]
Or
if condition {
f(...)
} else {
g(...)
}
vs.
var boolToFunc = map[bool]func(...){true: f, false: g}
...
boolToFunc[condition](...)
However, currently, the map form is much less efficient than the if-else block form:
package main
import (
"testing"
)
func f(x bool) int {
if x {
return 1
} else {
return 0
}
}
var m = map[bool]int{true: 1, false: 0}
func g(x bool) int {
return m[x]
}
var fr, gr int
func Benchmark_f(b *testing.B) {
for i := 0; i < b.N; i++ {
fr = f(true)
fr = f(false)
}
}
func Benchmark_g(b *testing.B) {
for i := 0; i < b.N; i++ {
gr = g(true)
gr = g(false)
}
}
Benchmark_f-4 1000000000 0.7478 ns/op
Benchmark_g-4 19250287 60.28 ns/op
Maps with bool keys could contain at most two entries, so I think it will be not hard to make optimizations for them.
If this could be implemented, it will be much helpful to improve performance for some Go programs.