Puerto AGP
Puerto AGP

Reputation: 423

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) {
case 9:
return true;
break;
case 16:
return true;
break;
case 17:
return true;
break;
case 18:
return true;
break;
case 20:
return true;
break;
case 37:
return true;
break;
case 38:
return true;
break;
case 39:
return true;
break;
case 40:
return true;
break;
default:
return false;
break;
}
}


function isSpecialKey(k) {
var arr = [9, 16, 17, 16, 8, 20, 37, 38, 39, 40]
for (i = 0; i < arr.length; i++) { if (k == arr[i]) { return true; } }
return false;
}

Upvotes: 1

Views: 3842

Answers (5)

Guffa
Guffa

Reputation: 700572

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

function isSpecialKey(k) {
  switch (k) {
    case 9:
    case 16:
    case 17:
    case 18:
    case 20:
    case 37:
    case 38:
    case 39:
    case 40:
      return true;
  }
  return false;
}

Consider also:

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

Upvotes: 2

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179159

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.

Upvotes: 2

Dave Newton
Dave Newton

Reputation: 160261

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

Upvotes: 0

Vivin Paliath
Vivin Paliath

Reputation: 95558

Instead of doing this, just create a map:

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

Then you can just test it like so:

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

Upvotes: 2

Pekka
Pekka

Reputation: 449613

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.

Upvotes: 4

Related Questions