case performance in ECMAscript

I'm using switch-case statements on regular bases in ECMAscript. Beside my personal endorsement about it, there is tons of specialist literature out, about performance in this language in general and about conditional statements specifically.

One good example I remember for instance, is the excellent book "High Performance Javascript" by Nicholas Zakas. Like in many other books and articles, it is said that a switch-case statement is always faster than if (else) statements, when you're using more than two conditional cases.

In any C-like language I know of, a switch-case statement is nothing else than a binary-hash-map which, broken down again, is a chain of jmp codes in assembly. Have a good read here

However, after this foreword:

I had a discussion about the usage of event handler functions with my team and how we are going to deal with event types. Whether or not we are going to use an explicit function for any event, or if we should use one big function which handles multiple event types. Within that discussion, the performance question developed and we created a very basic, simple jsPerf:

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

And I was pretty much shocked about the results and what I saw. Believing in these test-cases, the order of case statements is drastically important on the performance of execution. The difference between long and longSlow there, only is the position of the case 'baz' statement within the switch statement. Is this for real and reasonable?

Is there any chance I overlook something ? First, I thought well, maybe its not enough case statements and the interpreter will just create if-else conditions under the hood, so I increased the number without any change in results.

I just refuse to believe that ECMAscript engines like V8 and spidermonkey, still don't optimize this issue.


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

Use the if statement when:

  • There are no more than two discrete values for which to test.

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

  • Use the switch statement when:

  • There are more than two but fewer than 10 discrete values for which to test.

  • There are no ranges for conditions because the values are nonlinear.

  • Use array lookup when:

  • There are more than 10 values for which to test.

  • The results of the conditions are single values rather than a number of actions to be taken.

  • 链接地址: http://www.djcxy.com/p/71198.html

    上一篇: 在ExtendScript中获取错误的堆栈跟踪

    下一篇: ECMAscript中的案例性能