Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch vs object lookup performance (since jsperf is down)

The way I see it, for certain situations, there are two ways to do something if some value equals something: a switch or an object lookup.

Using a switch:

var value = ["Hello", "hi", "bYe", "die"][Math.floor(Math.random() * (4))];

switch (value.toLowerCase()) {
  case "hello":
    alert(value + "\n\n" + "hi");
    break;
  case "hi":
    alert(value + "\n\n" + "hello");
    break;
  case "bye":
    alert(value + "\n\n" + "no");
    break;
  case "die":
    alert(value + "\n\n" + "you shot me");
    break;
}

Using an object lookup:

var value = ["Hello", "hi", "bYe", "die"][Math.floor(Math.random() * (4))];

var LOOKUP = {
  "hello": function(v) {
    alert(v + "\n\n" + "hi");
  },
  "hi": function(v) {
    alert(v + "\n\n" + "hello");
  },
  "bye": function(v) {
    alert(v + "\n\n" + "no");
  },
  "die": function(v) {
    alert(v + "\n\n" + "you shot me");
  },
};

LOOKUP[value.toLowerCase()](value);

I am wondering which would have better performance?

And would there be any unobvious issues/gotchas with either approach?

like image 539
IMTheNachoMan Avatar asked Jun 09 '16 15:06

IMTheNachoMan


People also ask

Is switch faster than if else JS?

if-else Versus switch As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large.

What can I use instead of a switch case?

Luckily, JavaScript's object literals are a pretty good alternative for most switch statement use-cases I can think of. The idea is to define an object with a key for each case you would have in a switch statement. Then you can access its value directly using the expression you would pass to the switch statement.

When should you use a switch statement versus an IF ELSE statement Comment your answer in your JS file?

When you have to choose which one to use, it's based on readability and the expression that the statement is testing. Basically, an if else is used for taking a decisions while a switch statement is used to test the value of the given variable against a list of case value .


1 Answers

ORIGINAL ANSWER: A Lookup Table is much, much faster.

UPDATED ANSWER 2020: The two methods perform pretty much the same in modern browsers, with the switch statement being 20-30% faster than the lookup table.

I had the same question a while back. If jsperf ever gets revived, this is the link. https://jsperf.com/if-switch-lookup-table/10

Edit: Working benchmark https://jsben.ch/JYZLQ

like image 156
Dan Avatar answered Oct 06 '22 07:10

Dan