Example: I want to see if a key press is one of 4 different keys.
Option 1:
if(e.key === "ArrowUp" ||
e.key === "ArrowDown" ||
e.key === "Control" ||
e.key === "Escape" || ){
// do stuff
}
vs
switch(e.key){
case "ArrowUp":
case "ArrowDown":
case "Control":
case "Escape":
// do stuff
break;
default:
break;
}
There are many resources out there showing that a switch statement is more performant than multiple ifs. But what about a single if with multiple ORs vs a switch statement?
2
Answers
It was suggested to run some benchmarks and also include
includes
so here they are:Results (in ms):
Plotted (lower = better):
It seems like the answer is:
includes
is less performant with scaleor
performs the best (wins by 11ms)switch
performs the best (wins by 20ms)or
is juuust better thanswitch
by 3msMoral of the story: don't use
includes
,switch
is the way to go for the worst case scenario,or
is the way to go for best case scenario.@Null Salad, as you mentioned, the switch-case statement is generally more performant than an if-else statement, especially when dealing with large if-else ladders compared to their equivalent switch representation. You can find more details here
In this particular case, if you have a small number of conditions, the performance difference between if-else and switch-case is negligible. The only factor that matters is readability, and personally, I find if-else to be the better option.