Javascript performance: switch or if nested?

Asked

Viewed 2,214 times

9

Which of the two alternatives provides the best performance in Javascript: nested switch or if?

if {
  ...
} else {
  if {
    ...
  } else {
    if {
      ...
    } else {
      ...
    }
  }
}

or

switch(expression) {
    case n:
        code block
        break;
    case n:
        code block
        break;
    default:
        default code block
}
  • 1

    Why did they deny his question? It is not broad and easily explained with benchmarks, without having a basis in opinions. I was positive, the question is relevant. =)

  • I did not negatively, but the benchmark could be the assumption of the question. And the question is why the results.

  • What is the question after all? the only phrase that exists in the post does not tell me exactly what the question is, as intuitive as it is. It could be, which of the two is more beautiful in the code, which of the two is slower, which of the two is faster, which of the two is more used... anyway. For that reason I have denied.

  • @Marciano I edited to make it clearer, but even before I spoke about performance.

1 answer

8

Incredible as it may seem, the else-if is the most performatic among the possible options.

In this and in this benchmark, we analyze that Chrome performs better else-if almost browser version independent.

The benchmark is a technical evaluator. Logically, the else-if is a simple and explitic condition, while the switch, as trivial as it may seem, it has complex (more) criteria behind it - it is sensitive and intelligent because it can make implicit decisions, as is the case of the controller default and the case worthless. A else-if, for example, you cannot, of course, determine a default case - you must do this without subjection; you must do this by explicitly indicating in your code.

Simply put, the switch has a more complex algorithm behind it to enable it to make some decisions without having to explain. It is more autonomous; more independent. The else-if does so only if someone says so.

See the following example:

var foo = 1;
switch (foo) {
    case 0:
    case 1:
    case 2:
    case 3:
        alert('yes');
        break;
    default:
        alert('not');
}

Even if we don’t use the default, as in the following example, the implementation of the switch will be ready if we use it. So it’s convex - if we don’t use something, it’s there anyway, and it requires hardware; it requires arm. See:

var foo = 1;
switch (foo) {
    case 0:
    // [...]
}

A else-if, on the other hand, does not possess these "jokers". He will only treat what you tell him to do, otherwise he is hostile. In short, still at else-if, there are no prepared things that can "fatten" your solution if you don’t use it - and this makes it simpler and almost that consequently more performatic.

Practical contextualization

The switch holds the keys reserved case, default e et cetera. If we stop to think, it needs to know what to do when the developer calls for default and when to grant conditions to cases.

If the developer does not assign anything to default, no problem! It has a standard of treatment when this occurs - and what does this standard demand? More code, more logic and finally more performance. Like I said, the else-if is more objective and "dumb" - he needs you to explain everything you should do because he is not smart enough to make autonomous decisions, which diverges from a switch.

About Javascript processors

As you can see, the previously mentioned benchmark consists of Google’s browser, Chrome, which has the V8 engine as a processor.

Each engine has its own compilation mechanism, and these mechanisms can assume more or less performatic commitments depending on their structure and implementation. The point I want to make is that in the case of Chrome, else-if is "unbeatable" because in the dressing rooms things work in a specific way that gives this merit to him.

On the other hand, in this benchmark, he evaluates how the switch a better performance option if related to ifs in Firefox. Why this? Compiler. More than the implementation of switch there, the philosophy of development is another.

else-if or switch, after all?

In my opinion, for the fact of Chrome be used more than Firefox and any other browser, I would go from else-if on the theme performance.

The switch, in some cases, it is more semantic and its applicability stands out: if your search is this - what escapes the scope of the question -, then go with it.

Potential lies

To strengthen my response, I anticipate something that the user Maniero mentioned in the comments: benchmarks are extremely relative, mainly from modern navigators. If you look at the benchmarks I’ve shared, it’s easy to spot a very large oscillation in results throughout browser versions.

My point is: not that benchmarks are unreliable, but they are not fully trusted. As I replied to Maniero, the ideal is to use statistics as a little base and reference, but not as the definitive solution to peace.

  • I ran the benchmark here and it showed that the difference between switch and if-Else is 0.2% (sometimes for one, sometimes for another). Negligible. Can show why "Chrome performs better in Else-if conditions"?

  • For me the switch won... :p

  • Are you using Firefox? If so, excuse me - I let it go unnoticed. I took a better approach to my thesis (?). Look now.

  • @Guilhermeoderdenge I executed using Chrome 35.

  • @Guilhermebernal I also ran with Chrome 35 and had 685kk ops/sec on else-if against 587kk ops/sec no switch. As far as I know - and also according to jsperf - Higher is Better.

  • 2

    Liar! Liar! Liar! Benchmarks are liars! Benchmarks only work under specific conditions. Without good environmental control, benchmark can vary greatly. And a browser, mainly modern, it is a very unstable environment. It is possible to do benchmark in it, but it is no easy task. It would be nice to have something canonical to do benchmark in browsers. The issue improved understanding. And usage statistics are also liars. You are happy to: https://www.netmarketshare.com/browser-market-share.aspx?qprid=0&qpcustomd=0 I only trust the access statistics of my website. And look there.

  • @bigown I agree with you - statistics are "liars". The point is: the ideal is always try get as close to things as possible - and I think the benchmark helping He doesn’t need anything, but it helps.

  • +1 by the jsperf.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.