This program has a func that changes some byte values into other byte values. We can either use a switch to do this, or a generated lookup table.
package main
import (
"fmt"
"time"
)
var (
lut [128]byte
)
func GetLookupValue(x byte) int {
switch x {
case '#', 'P':
return 130
case 'i':
return 70
case 'p':
return 10
}
return 0
}
func main() {
// Initialize lookup table.
for z := 0; z < 128; z += 1 {
lut[z] = byte(GetLookupValue(byte(z)))
}
data := []byte(
"abc#Pip123###")
t0 := time.Now()
// Version 1: use switch to get value.
result := 0
for i := 0; i < 10000000; i++ {
for _, x := range data {
result += GetLookupValue(x)
}
}
t1 := time.Now()
// Version 2: use lookup table.
result2 := 0
for i := 0; i < 10000000; i++ {
for _, x := range data {
result2 += int(lut[x])
}
}
t2 := time.Now()
// Benchmark results.
fmt.Println(result, result2)
fmt.Println(t1.Sub(t0))
fmt.Println(t2.Sub(t1))
}
7300000000 7300000000
220.894417ms (Switch)
64.784ms (Lookup)