Skip to content Skip to sidebar Skip to footer

Should I Use Big Switch Statements In Javascript Without Performance Problems?

I've google'd a bit but I still feel to be lost. I am writing a CPU emulator in JavaScript (namely Z80 in me case, currently). There is a huge switch statement in its heart. Though

Solution 1:

The switch is at least as fast as having to evaluate many ifs and elses. Even without knowing the insides of JavaScript engines and optimizers, this we know for sure.

In case of an interpreter such as your case, it might be even better to store functions in a dictionary (array) instead, and do a binary lookup of your code in that array.

So create an array with the code you would put in the cases as index and JavaScript code (functions) as values, and just execute the code you find at the array.

Solution 2:

switch is clearly going to be faster than if-else, since it runs in constant time, only requiring a single lookup. The ambiguous case might be for lookup tables.

I've modified an existing test-case for jsperf for you to compare:

http://jsperf.com/if-switch-lookup-table/18

The lookup table implementation is the fastest of the three.

Solution 3:

At around 1000 iterations and random sampling, if and switch bounce around each other. The difference varies about 5% to 15%. It probably wouldn't be noticeable. When you bump that up to 100000, then switch always wins, by around the same %. That's to be expected, since switch reads once and compares against many, while if reads many and compares against many.

But what is noticeable is using a new Map() object to find a result completely blows away either of them.

https://jsperf.com/get-speed-comparison

Solution 4:

Switch is much slower than map lookup in all modern browsers when there are many cases to check. See the benchmarks:

Post a Comment for "Should I Use Big Switch Statements In Javascript Without Performance Problems?"