Switch Case Performance in ECMAscript

I use switch-case on regular bases in ECMAscript. In addition to my personal approval, there are tons of specialized literature on performance in this language as a whole and on conditional statements specifically.

One good example that I remember, for example, is the excellent book "High Performance Javascript" by Nicholas Zakas. Like many other books and articles, it says that the switch-case always faster than the if (else) when you use more than two conditional cases.

In any C-like language that I know of, the switch-case is nothing more than a binary hash map, which, broken again, is the jmp code chain in the assembly. Read well here

However, after this introduction:

I had a discussion about using the event handler functions with my team and how we will deal with event types. Will we use an explicit function for any event or use one large function that processes several types of events. As part of this discussion, a performance issue was developed, and we created a simple, simple jsPerf:

http://jsperf.com/engine-context-data-caching-test/3

And I was very shocked by the results and what I saw. Assuming in these tests, the order of case statements is critical when executing execution. The difference between long and longSlow there, only the position of the case 'baz' statement in the switch . Is this really and reasonable?

Is there a chance to miss something? First, I thought well, maybe it is not enough for case , and the interpreter will simply create if-else under the hood, so I increased the number without any changes in the results.

I simply refuse to believe that ECMAscript engines such as V8 and spidermonkey still do not optimize this problem.

+7
source share
1 answer

I refer to this source: http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#sect2

Use the if statement if:

  • There are no more than two discrete values ​​for testing.

  • There are a large number of values ​​that can be easily divided into ranges.

Use the switch statement when:

  • There are more than two, but less than 10 discrete values ​​for testing.

  • There are no ranges for conditions, because the values ​​are non-linear.

Use array search when:

  • There are more than 10 values ​​for testing.

  • The results of the conditions are single values, not a series of actions that need to be taken.

+4
source

All Articles