Skip to content

Instantly share code, notes, and snippets.

@tiancaiamao
Last active January 13, 2018 12:13
Show Gist options
  • Save tiancaiamao/28fd53ff9b29eaac30f84b4ba04e2e7e to your computer and use it in GitHub Desktop.
Save tiancaiamao/28fd53ff9b29eaac30f84b4ba04e2e7e to your computer and use it in GitHub Desktop.
Performance comparison between switch statement and jump table
package main
import "fmt"
import "time"
import "math/rand"
var jumpTable = [32]func(){
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
noop, noop, noop, noop,
}
func noop() {
}
func runJumpTable(code []uint32) {
for _, c := range code {
jumpTable[c]()
}
}
func runSwitch(code []uint32) {
for _, c := range code {
switch c {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
case 31:
}
}
}
func main() {
var code [5000]uint32
for i := 0; i < 5000; i++ {
code[i] = rand.Uint32() % 32
}
t := time.Now()
runSwitch(code[:])
fmt.Println("switch cost:", time.Since(t))
t = time.Now()
runJumpTable(code[:])
fmt.Println("jumt table cost:", time.Since(t))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment