Should I Use Big Switch Statements In Javascript Without Performance Problems?
Solution 1:
The switch
is at least as fast as having to evaluate many if
s and else
s. 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.
Solution 4:
Switch is much slower than map lookup in all modern browsers when there are many cases to check. See the benchmarks:
- https://jsbench.me/k4k7iqxeui Sequential numeric keys
- https://jsbench.me/izk7irbif6 Random numeric keys
- https://jsbench.me/jck7iruqq5 Random string keys
- https://jsbench.me/3sk7is2v04 Function values
Post a Comment for "Should I Use Big Switch Statements In Javascript Without Performance Problems?"