javascript - switch-case performance in ECMAscript -
i'm using switch-case
statements on regular bases in ecmascript. beside personal endorsement it, there tons of specialist literature out, performance in language in general , conditional statements specifically.
one example remember instance, excellent book "high performance javascript" nicholas zakas. in many other books , articles, said switch-case
statement faster if (else)
statements, when you're using more two conditional cases.
in c-like language know of, switch-case
statement nothing else binary-hash-map which, broken down again, chain of jmp codes in assembly. have read here
however, after foreword:
i had discussion usage of event handler functions team , how going deal event types. whether or not going use explicit function event, or if should use 1 big function handles multiple event types. within discussion, performance question developed , created basic, simple jsperf:
http://jsperf.com/engine-context-data-caching-test/3
and pretty shocked results , saw. believing in these test-cases, order of case statements
drastically important on performance of execution. difference between long
, longslow
there, position of case 'baz'
statement within switch
statement. real , reasonable?
is there chance overlook ? first, thought well, maybe not enough case
statements , interpreter create if-else
conditions under hood, increased number without change in results.
i refuse believe ecmascript engines v8 , spidermonkey, still don't optimize issue.
i'm referencing source: http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#sect2
use if statement when:
there no more 2 discrete values test.
there large number of values can separated ranges.
use switch statement when:
there more 2 fewer 10 discrete values test.
there no ranges conditions because values nonlinear.
use array lookup when:
there more 10 values test.
the results of conditions single values rather number of actions taken.