Switch vs. hash

JavaScript performance comparison

Revision 8 of this test case created by layane

Info

Is a hash (array) really faster than a switch?

Preparation code

<script>
  var theVar = 'j';
 
  var cases = {
   a: 'a',
   b: 'b',
   c: 'c',
   d: 'd',
   e: 'e',
   f: 'g',
   h: 'h',
   i: 'i',
   j: 'j'
  };
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Switch
switch (theVar) {
case 'a':
 'a';
 break;
case 'b':
 'b';
 break;
case 'c':
 'c';
 break;
case 'd':
 'd';
 break;
case 'e':
 'e'
 break;
case 'f':
 'f';
 break;
case 'g':
 'g';
 break;
case 'h':
 'h';
 break;
case 'i':
 'i';
 break;
case 'j':
 'j';
 break;
default:
 'default';
 break;
}
pending…
Hash
if (!cases[theVar]) {
 'default';
}
pending…
Falsy Default
(cases[theVar] || 'default');
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment