The author never claimed that shorter code, which is just a hash map of possible cases, would actually be faster. Obviously, creating an array adversely affects performance when run in a test suite. At the same time, the switch is compiled code.
You will see some improvement if your code is reused, i.e. you save the value of cases ; I measured the difference by about 20-30% in this test case , depending on which case happens more often.
However, an isolated performance test such as this one will not be useful if your code is not running inside a hard loop because the test cases run at 50 M + operations per second on my home computer. Therefore, the differences between them should be based on other factors, such as code clarity or the fact that switch easy to mess up if you forget to place the break; statement break; .
Ja͢ck
source share