I saw a post on http://www.jquery4u.com/javascript/shorthand-javascript-techniques/ where he talks about an alternative way to using switch statements.
I have created a snippet below, but I'm not sure why the alternate is 99% slow.
function doX(){}
function doY(){}
function doN(){}
var something = 1;
var cases = {
1: doX,
2: doY,
3: doN
};
if (cases[something]) {
cases[something]();
}
http://jsperf.com/alternateswitch
Any idea?
That "JSON" syntax is just an object. Also, your comparison is a little unfair here, as you create a brand new object every single timed loop, which is somewhat expensive.
If you move the object creation to the setup section, the speed difference becomes neglibile: http://jsperf.com/alternateswitch/4
If you remove the if
statement, the object will be a tad faster (at least for me): http://jsperf.com/alternateswitch/5. The extra property lookup and truthiness check does slow it down.
The author never claimed the shorter code, which is just a hash map of the possible cases, would actually be faster. Obviously, the array creation negatively impacts the performance when you run it in a test suite. At the same time, the switch
statement is compiled code.
You will see some improvement if your code is being reused, i.e. you keep the value of cases
; I've measured a difference of about 20-30% in this test case, depending on which case occurs more often.
That said, an isolated performance test such as this won't be useful unless your code is run inside a tight loop, because the test cases run at 50M+ operations per second on my home computer. Differences between the two should therefore be based on other factors, such as code clarity or the fact that switch
statements are easy to mess up if you forget to place break;
a statement.
switch
, you make that the variable you are looking for is at the first case. Therefore, the complexity for switch
is O(1) for your testing.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With