157

Guys I have a couple of questions:

  1. Is there a performance difference in JavaScript between a switch statement and an if...else?
  2. If so why?
  3. Is the behavior of switch and if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

The reason for asking this question is it seems that I get better performance on a switch statement with approx 1000s cases in Firefox.


Edited Unfortuantly this is not my code the Javascript is being produced serverside from a compiled library and I have no access to the code. The method that is producing the javascript is called

CreateConditionals(string name, string arrayofvalues, string arrayofActions)

note arrayofvalues is a comma separated list.

what it produces is

function [name] (value) {
  if (value == [value from array index x]) {
     [action from array index x]
  }
}

Note: where [name] = the name passed into the serverside function

Now I changed the output of the function to be inserted into a TextArea, wrote some JavaScript code to parse through the function, and converted it to a set of case statements.

finally I run the function and it runs fine but performance differs in IE and Firefox.

danwellman
  • 8,179
  • 6
  • 49
  • 75
John Hartsock
  • 78,484
  • 22
  • 123
  • 143
  • 1
    I would suggest a code sample to examine what's optimal. I mean, there's gotta be a reason you're asking this, right? – jcolebrand May 27 '10 at 16:34
  • 1
    Please post what you're up to, because there are very few cases in my long experience for which I'd say a 100-case switch statement or a 100-part if/else series was a good idea. – Pointy May 27 '10 at 16:40
  • sorry guys not 100s but thousands of conditions – John Hartsock May 27 '10 at 17:04
  • 3
    Everyone, thanks for the input. But my problem wasnt actually the difference between the if and swith statments. It was the code running inside the statement. +1 to all of you for your help. Sorry for the inconvienience. Sometimes you just need to talk things out with another person to find the solution. – John Hartsock May 27 '10 at 17:34

9 Answers9

119

Answering in generalities:

  1. Yes, usually.
  2. See More Info Here
  3. Yes, because each has a different JS processing engine, however, in running a test on the site below, the switch always out performed the if, elseif on a large number of iterations.

Test site

Fcmam5
  • 1,461
  • 13
  • 22
Tommy
  • 38,021
  • 8
  • 85
  • 116
  • Thanks tommy your example site was nice to use when trying to determine what the performance difference was between if and switch. Its so minimal it led me to the conclusion that my problem was elsewhere, as I noted in my comment with my question. Thanks for your time. – John Hartsock May 27 '10 at 17:36
  • 1
    If you want a TLDR of when to use which conditionals here is a direct link to a segment in the article addressing that: http://oreilly.com/server-administration/excerpts/even-faster-websites/writing-efficient-javascript.html#the_fastest_conditionals – edhedges May 06 '13 at 13:43
  • 2
    @Tommy Good article, thanks for sharing. However the article states that there is a negligible performance difference between `switch` and `if/then` statements in JS. The article states this is due to spotty `switch` optimization and the different ways different JS engines function. Quote: `Since most JavaScript engines don’t have such optimizations, performance of the switch statement is mixed.` – Jasper May 17 '13 at 17:23
  • @Jasper, thanks! But, I wanted to point out from the O'Reily article it also states: *...if statements are generally faster than switch statements when there are just one or two conditions to be evaluated. When there are more than two conditions, and the conditions are simple (not ranges), the switch statement tends to be faster. This is because the amount of time it takes to execute a single condition in a switch statement is often less than it takes to execute a single condition in an if statement, making the switch statement optimal only when there are a larger number of conditions.* – Tommy May 17 '13 at 18:36
  • @Jasper - And agreed, it isn't rock solid conclusion, but that's why I mentioned I was answering in generalities:) – Tommy May 17 '13 at 18:38
  • 3
    Is anything quantifiable shown in this description? It reads like a lot of "best practices/premature optimization" conjecture. It was also written 7 years ago, so javascript optimizations have changed tremendously in this time. In compiled languages, the performance difference between these three operations is "almost never significant enough to care". Don't bother optimizing things that won't affect actual performance. Optimize readability. – Thomson Comer Feb 01 '16 at 21:01
  • @ThomsonComer - those are valid points but I am not sure what do about it from my perspective? Thats not a snarky comment, but rather, a solicitation of input - do you have a suggestion on how to improve this answer 7 years later? – Tommy Feb 01 '16 at 21:35
  • Well, for the first time in just about that long, I found myself asking the same as the original question. After seven years, I feel like a voice saying, "Don't premature optimize" isn't unreasonable. Especially for junior level programmers, this is not the kind of question you need to be worrying yourself with. :) Your answer is solid. – Thomson Comer Feb 01 '16 at 22:08
  • Test gives me infinity for some cases, probably because it optimizes away empty statements. I tried to make a new revision – actually I added two, but they have no test cases. I don't know why it won't save my changes. It just tells me sometimes not all test cases were saved or to review some fields it doesn't mark for me in any way. I guess the internet needs a new performace testing site. – Neonit Apr 25 '18 at 13:54
  • 3
    @Tommy «[See More Info Here](https://www.oreilly.com/library/view/high-performance-javascript/9781449382308/ch04s02.html)» gives 404, what was there? – LogicDaemon Jan 05 '19 at 16:12
  • 2
    @LogicDaemon - IIRC is was a link to some oRielly textbox that got into some indepth JS performance considerations / discussions – Tommy Jan 07 '19 at 21:27
  • As you can see form the browserscope stats, your claim that `switch` is faster is not true. Please modify your answer or the benchmark. – FINDarkside Jan 23 '19 at 16:00
  • As I look at the most recent version of the test (revision 10 - https://jsperf.com/switch-case-vs-if-else/10), it has additional cases added after the revisions with only 3 cases. Seems with 10 cases, the switch kills if/else especially on newer versions of Chrome (>70). This shows that your mileage may vary in usage scenarios but I still have never found an instance where switch is significantly slower than if/else (whereas Ive seen the opposite on current metrics) so I still feel confident in saying "yes, usually there is a performance difference" and typically, the switch is faster. – Tommy Jan 23 '19 at 21:13
  • 1
    i've just added one with 10 cases. https://jsperf.com/switch-case-vs-if-else/24 And it appears that they are so close in terms of performance, They are within <1% of each other (they are all marked "fastest"). It comes down to preferred syntax. – etoxin Aug 26 '19 at 05:21
  • weird. it actually says `if-else again` was the fastest – oldboy Feb 07 '20 at 23:53
  • @oldboy - I mean it is a 10 year old answer and JS engines have been greatly improved / modified / changed in those 10 years. :) IMHO, It is still both browser dependent as well as "function" dependent, meaning, number of cases, amount of work in comparisons, etc. – Tommy Feb 08 '20 at 16:58
  • i think the single rule of thumb is simply to reduce calculations and repetition in order to increase performance. hence `switch` must be more efficient when youre evaluating the same value repeatedly (i.e. `v === 1 else if v === 2 else if v === 3 else if`, etc), generally speaking. – oldboy Feb 09 '20 at 01:08
66

Sometimes it's better to use neither. For example, in a "dispatch" situation, Javascript lets you do things in a completely different way:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

Setting up multi-way branching by creating an object has a lot of advantages. You can add and remove functionality dynamically. You can create the dispatch table from data. You can examine it programmatically. You can build the handlers with other functions.

There's the added overhead of a function call to get to the equivalent of a "case", but the advantage (when there are lots of cases) of a hash lookup to find the function for a particular key.

Pointy
  • 371,531
  • 55
  • 528
  • 584
  • 3
    Your strategy is good and I use it oftenly. But as pointed by @Michael Geary https://stackoverflow.com/a/45336805/5936119, the map variable must be declared outside the dispatch context otherwise it will always be re-evaluated. – Daniel Santana Jan 24 '19 at 10:38
  • @DanielSantana true but I doubt that's significantly expensive. In particular, once a function is initially parsed the *code* itself need not be regenerated, as the text is static. – Pointy Jan 24 '19 at 13:41
22

The performance difference between a switch and if...else if...else is small, they basically do the same work. One difference between them that may make a difference is that the expression to test is only evaluated once in a switch while it's evaluated for each if. If it's costly to evaluate the expression, doing it one time is of course faster than doing it a hundred times.

The difference in implementation of those commands (and all script in general) differs quite a bit between browsers. It's common to see rather big performance differences for the same code in different browsers.

As you can hardly performance test all code in all browsers, you should go for the code that fits best for what you are doing, and try to reduce the amount of work done rather than optimising how it's done.

Guffa
  • 640,220
  • 96
  • 678
  • 956
7

Other than syntax, a switch can be implemented using a tree which makes it O(log n), while a if/else has to be implemented with an O(n) procedural approach. More often they are both processed procedurally and the only difference is syntax, and moreover does it really matter -- unless you're statically typing 10k cases of if/else anyway?

user157251
  • 64,489
  • 38
  • 208
  • 350
  • 1
    7 years later... I don't see how tree implementation is possible, except in a the case of constant numerical case values). – Ed Staub Feb 11 '17 at 15:03
  • 3.5 years later... @Ed Staub Of course that is the case here. Switch statements work with constants. Wether already numbers or whatever, they can be enumerated, so a tree can be constructed. – trollkotze Nov 09 '20 at 13:56
  • @trollkotze While constants are most common, case clauses can be any expression. See e.g. https://stackoverflow.com/questions/3463833/expression-inside-switch-case-statement. – Ed Staub Nov 10 '20 at 14:38
  • Oh, I didn't know that. It's not possible in C, afaik. Only constant expressions allowed there. So I assumed it to be the same in JS. – trollkotze Nov 11 '20 at 18:01
6
  1. If there is a difference, it'll never be large enough to be noticed.
  2. N/A
  3. No, they all function identically.

Basically, use whatever makes the code most readable. There are definitely places where one or the other constructs makes for cleaner, more readable and more maintainable. This is far more important that perhaps saving a few nanoseconds in JavaScript code.

Jon Benedicto
  • 10,206
  • 3
  • 26
  • 30
  • 5
    In javascript especially, the semantics and readability (and therefore the maintainability) trump any localized performance differences between `if..else` and `switch` caused by a unique browser version computer hardware and OS combination. – jball May 27 '10 at 16:40
  • 2
    I don't know if I agree, it might indeed be noticed if it is used in a loop with say, a large database, traversing a tree etc. – ghoppe May 27 '10 at 16:50
  • 3
    i definitely disagree. as web applications become more and more complex, this difference could be significant for the application and could change dependent on browsers. – joshvermaire Nov 22 '11 at 23:52
  • 7
    The important thing is to write clean, maintainable code. When a performance issue is seen - profile. Then determine which code to fix. Don't sacrifice maintainability for assumed performance issues. – Jon Benedicto Nov 23 '11 at 14:09
  • 3
    'if else if else ...' is O(n), while 'switch' is either O(1) or O(log(n)). How can you honestly state the difference can never be large enough? Have a million of cases in switch (easily possible if the code is generated) and you'll definitely notice it to say the least. – dragonroot May 09 '12 at 05:11
  • @dragonroot, the performance of if and switch is completely dependant on the implementation of the JavaScript engine. There's no guarantee that if/else is O(n) and switch is O(1) or O(log(n)) in all engines. As I said before, you cannot assume performance issues. They have to be discovered with profiling, especially with something small like an if/else vs switch statement. – Jon Benedicto May 09 '12 at 13:35
  • 1
    @Jon Benedicto, 'switch' was specifically designed to be easily implementable faster than O(n) - its syntax is not just syntactic sugar. 'if's were supposed to be evaluated one after another, on the other hand. – dragonroot May 22 '12 at 04:08
  • 1
    If you have calculations that are not time sensitive than sure - go for what you can read best. However, if you are going through large sets of data, or running intense calculations continuously, than you should care less about readability and instead look for what is most CPU friendly. I do believe switch statements are faster still in many circumstances but in others, not as fast. – Jonathan Tonge Feb 10 '13 at 15:42
  • 3
    I downvoted this because I think the generalization made in answer to the first question is incorrect. – thatmiddleway Mar 17 '14 at 21:06
6

Pointy's answer suggests the use of an object literal as an alternative to switch or if/else. I like this approach too, but the code in the answer creates a new map object every time the dispatch function is called:

function dispatch(funCode) {
  var map = {
    'explode': function() {
      prepExplosive();
      if (flammable()) issueWarning();
      doExplode();
    },

    'hibernate': function() {
      if (status() == 'sleeping') return;
      // ... I can't keep making this stuff up
    },
    // ...
  };

  var thisFun = map[funCode];
  if (thisFun) thisFun();
}

If map contains a large number of entries, this can create significant overhead. It's better to set up the action map only once and then use the already-created map each time, for example:

var actions = {
    'explode': function() {
        prepExplosive();
        if( flammable() ) issueWarning();
        doExplode();
    },

    'hibernate': function() {
        if( status() == 'sleeping' ) return;
        // ... I can't keep making this stuff up
    },
    // ...
};

function dispatch( name ) {
    var action = actions[name];
    if( action ) action();
}
Michael Geary
  • 26,814
  • 8
  • 56
  • 71
2

Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)

Sarfraz
  • 355,543
  • 70
  • 511
  • 562
1

It turns out that if-else if generally faster than switch

http://jsperf.com/switch-if-else/46

sidonaldson
  • 20,187
  • 10
  • 47
  • 54
1
  1. Workbenching might result some very small differences in some cases but the way of processing is browser dependent anyway so not worth bothering
  2. Because of different ways of processing
  3. You can't call it a browser if the behavior would be different anyhow
Koen
  • 3,505
  • 1
  • 31
  • 52