Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON like syntax vs switch statement javascript

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?

like image 464
Arun Avatar asked Aug 20 '13 16:08

Arun


3 Answers

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.

like image 56
Blender Avatar answered Nov 13 '22 22:11

Blender


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.

like image 3
Ja͢ck Avatar answered Nov 13 '22 20:11

Ja͢ck


  • I believe that Javascript object is an associative array which usually implemented as a hash table. Each lookup requires a key to go through a hashing function. Hashing function is like a double blade. For a small size data, it would be slower than a if-elseif-else. However, for larger data, it will outperform ordinary if-elseif-else
  • It is very unfair that you are favoring the 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.
like image 3
invisal Avatar answered Nov 13 '22 22:11

invisal