Reputation: 1017
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?
Upvotes: 7
Views: 2353
Reputation: 173642
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.
Upvotes: 3
Reputation: 298432
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.
Upvotes: 8
Reputation: 9427
Usually switch
statements are optimized by the compiler/interpreter. They are even faster than chained if-else
statements. By using a JSON
object instead of switch
statement, you're bypassing the Javascript engine optimization.
Upvotes: 1
Reputation: 11181
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.Upvotes: 3