JSON as syntax versus switch javascript statement

I saw a post at http://www.jquery4u.com/javascript/shorthand-javascript-techniques/ , where he talks about an alternative way to use switch statements.

I created the snippet below, but I'm not sure why the alternative is 99% slower.

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?

+7
json javascript
source share
4 answers

The author never claimed that shorter code, which is just a hash map of possible cases, would actually be faster. Obviously, creating an array adversely affects performance when run in a test suite. At the same time, the switch is compiled code.

You will see some improvement if your code is reused, i.e. you save the value of cases ; I measured the difference by about 20-30% in this test case , depending on which case happens more often.

However, an isolated performance test such as this one will not be useful if your code is not running inside a hard loop because the test cases run at 50 M + operations per second on my home computer. Therefore, the differences between them should be based on other factors, such as code clarity or the fact that switch easy to mess up if you forget to place the break; statement break; .

+3
source share

The syntax "JSON" is just an object. Also, your comparison here is a little unfair, as you create a completely new object every single cycle, which is somewhat more expensive.

If you move the creation of an object to the settings section, the speed difference becomes careless: http://jsperf.com/alternateswitch/4

If you remove the if , the object will be a little faster (at least for me): http://jsperf.com/alternateswitch/5 . An additional property search and likelihood check slows down.

+7
source share
  • I believe that a Javascript object is an associative array, which is usually implemented as a hash table. Each search requires a key to navigate through the hash function. The hashing function is similar to a double blade. For small data, this will be slower than if-elseif-else. However, for big data, it will outperform regular if-elseif-else
  • It is very unfair that you prefer switch , you do that the variable you are looking for is in the first case. So the complexity for switch is O (1) for your testing.
+3
source share

Typically, switch optimized by the compiler / interpreter. They are even faster than if-else chains. Using a JSON object instead of a switch , you will bypass the Javascript engine optimization.

+1
source share

All Articles