Optimize Conditionals with a Branch Table

I learned a little trick today, courtesy of this answer on quora.

Basically, rather than using a bunch of if statements, you can use an array for each option.  For example, here’s some code I created to benchmark multiple if statements vs. a switch vs. a branch table:

testing branch tables
I tried a few different ways but the branch table is consistently fastest, with the case statement coming in second.

One thing about my benchmark tests is that the first two required an array lookup in the CHOICES constant, while the branch table doesn’t require this, so that could throw off the results.  So I tried a different test:

alternate benchmarkIt turns out that CHOICES lookup was a performance hit for the first two tests, but  the branch table was still faster.

This seems obvious in hindsight.  I’m kind of surprised I never learned it before now.