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?
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.
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 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 .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With