Performance of if-else, switch or map based conditioning

JavascriptSwitch StatementIf Statement

Javascript Problem Overview


I was wondering about the performances of the following implementations of conditional structs in javascript.

Method 1:

 if(id==="camelCase"){
    window.location.href = "http://www.thecamelcase.com";
}else if (id==="jsFiddle"){
    window.location.href = "http://jsfiddle.net/";
}else if (id==="cricInfo"){
    window.location.href = "http://cricinfo.com/";
}else if (id==="apple"){
    window.location.href = "http://apple.com/";
}else if (id==="yahoo"){
    window.location.href = "http://yahoo.com/";
}           

Method 2:

switch (id) {
case 'camelCase':
    window.location.href = "http://www.thecamelcase.com";
    break;
case 'jsFiddle':
    window.location.href = "http://www.jsfiddle.net";
    break;
case 'cricInfo':
    window.location.href = "http://www.cricinfo.com";
    break;
case 'apple':
    window.location.href = "http://www.apple.com";
    break;
case 'yahoo':
    window.location.href = "http://www.yahoo.com";
    break;

}

Method 3

var hrefMap = {
camelCase : "http://www.thecamelcase.com",
jsFiddle: "http://www.jsfiddle.net",
cricInfo: "http://www.cricinfo.com",
apple: "http://www.apple.com",
yahoo: "http://www.yahoo.com"
};
window.location.href = hrefMap[id];

Method 4

window.location.href = {
    camelCase : "http://www.thecamelcase.com",
    jsFiddle: "http://www.jsfiddle.net",
    cricInfo: "http://www.cricinfo.com",
    apple: "http://www.apple.com",
    yahoo: "http://www.yahoo.com"
}[id];

Probably Method 3 and 4 might have almost the same performance but just posting to confirm.

Javascript Solutions


Solution 1 - Javascript

According to this JSBen.ch test, the switch setup is the fastest out of the provided methods (Firefox 8.0 and Chromium 15).

Methods 3 and 4 are slightly less fast, but it's hardly noticeable. Clearly, the if-elseif method is significantly slower (FireFox 8.0).

The same test in Chromium 15 does not show significant differences in performance between these methods. In fact, the if-elseif method seems to be the fastest method in Chrome.

Update

I have run the test cases again, with 10 additional entries. The hrefmap (methods 3 and 4) show a better performance.

If you want to implement the compare method in a function, method 3 would definitely win: Store the map in a variable, and refer to this variable at a later point, instead of reconstructing it.

Solution 2 - Javascript

You can always do a jsPerf test yourself. However, in general a lookup table is the fastest way to access data. That would be (3) in your snippets. Also, switch/case is almost always faster than if-else. So the order for your example would be

(3) -> (4) -> (2) -> (1)

Solution 3 - Javascript

Performance diverges for conditional logic (rather than mere value lookup)

if-else vs switch vs map of functions vs class method dispatch

I think a lot of people come to this question, Performance of if-else, switch or map based conditioning, because they want to know how best to condition logic, as the title implies, rather than simple key-based value lookup.

My benchmark differs from the one in the accepted answer and also corrects a number of its flaws (further explanation at bottom below results table):

  1. Tests branched logic. i.e. conditional execution flow, not simple lookups.

  2. Branches randomly. A random sequence of branch keys is generated in setup. Each approach is then tested with the same sequence.

  3. Branch results aren't predictable. The logic result for each branch are not the same for other branches, nor are they the same for subsequent executions of the same branch.

  4. There are 11 branches. To me this question is more relevant to around that many. If there are much fewer, it doesn't make sense to consider anything other than if-else or switch.

  5. Re-used structures are initialized in setup rather than in the benchmarked code block.

This is what I got on Safari/macOS:

approach JSBench
if-else 100
switch 99+
map of functions ~90
class method dispatch ~85

I ran the same benchmark again with twice as many branches (22) expecting to see map to gain ground, and I got about the same results (though class method dispatch may be doing slightly relatively better). If I had time I'd write code to generate benchmark code so that I could graph a wide range of branch counts... but alas I don't.

Limitations in the question's sample code and benchmarks in the other answers and comments

The question's own sample code as well as the benchmarks code used in Rob W's answer and jAndy's answer only test value lookup. As expected, for a small set of keys those benchmarks show negligible performance differences; Any significant difference would have been a flaw in the JS engine. They do not demonstrate the issue of conditional logic.

In addition, as some have pointed out, there are other flaws in the benchmark code:

  • Performance only matters if the conditional logic is executed thousands of times. In such cases one would not reinitialize data structures each use.

  • The test code takes the same branch every time. This has two problems:

    • It does not reflect average cost (e.g. for an if-else or switch, earlier branches are cheaper, later are more expensive).

    • Compile-time or JIT optimization is likely to optimize it away, thereby producing misleading results (because in real code, the conditions would not be so predictable).

  • Each branch produces exactly the same result each time. And for the Rob W's benchmark, the result is the same as the input!

    • Of course a map will perform well for this usage. That's what they are designed for!

    • If you have conditional logic where the logic for each branch produced the exact same result each time, you should consider using memoization.

Solution 4 - Javascript

Just thought I'd add this as a possible consideration. I came across this doing research on this very question... http://davidbcalhoun.com/2010/is-hash-faster-than-switch-in-javascript

It takes different engines and browsers into account.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaditya_gaurView Question on Stackoverflow
Solution 1 - JavascriptRob WView Answer on Stackoverflow
Solution 2 - JavascriptjAndyView Answer on Stackoverflow
Solution 3 - JavascriptInigoView Answer on Stackoverflow
Solution 4 - JavascriptUbermonkView Answer on Stackoverflow