Skip to content Skip to sidebar Skip to footer

Javascript Switch Vs Loop On Array

I have these two functions and I want to know which one is faster. I assume the first one, but what if I have hundreds of cases to evaluate? function isSpecialKey(k) { switch (k) {

Solution 1:

It is very unlikely to matter, not even with hundreds of cases. It might start mattering with thousands or tens of thousands but in that case, you probably shouldn't be using JavaScript anyway! At least not in a web browser.

Generally - the second way is the only way that makes sense from a maintenance perspective. I would absolutely take that.

However, for your specific case, there is a better solution.

Solution 2:

Instead of doing this, just create a map:

varspecialKeys= {
    9:true,
    16:true,
    17:true,
    ...40:true
};

Then you can just test it like so:

if(specialKeys[value]) {
   ...
}

Solution 3:

How about?

function isSpecialKey(key) {
  return [9, 16, 17, 16, 8, 20, 37, 38, 39, 40].indexOf(key) > -1;
}

Update. I've just remembered there are some browsers that don't support indexOf on arrays, but I forgot which of them, so be careful.

Solution 4:

You can use fallthrough in the switch, which makes for a lot less code:

functionisSpecialKey(k) {
  switch (k) {
    case9:
    case16:
    case17:
    case18:
    case20:
    case37:
    case38:
    case39:
    case40:
      returntrue;
  }
  returnfalse;
}

Consider also:

functionisSpecialKey(k) {
  return (
    k == 9 ||
    k == 16 ||
    k == 17 ||
    k == 18 ||
    k == 20 ||
    k == 37 ||
    k == 38 ||
    k == 39 ||
    k == 40
  );
}

Solution 5:

Use a map; faster yet. "Hundreds" of switches should never come close to passing a code review.

Post a Comment for "Javascript Switch Vs Loop On Array"