Switch vs. hash

JavaScript performance comparison

Revision 3 of this test case created by David Calhoun

Info

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

Preparation code

<script>
  var theVar = 'j';
 
  var cases = [];
  cases['a'] = function() {};
  cases['b'] = function() {};
  cases['c'] = function() {};
  cases['d'] = function() {};
  cases['e'] = function() {};
  cases['f'] = function() {};
  cases['g'] = function() {};
  cases['h'] = function() {};
  cases['i'] = function() {};
  cases['j'] = function() {};
</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':
 cases['a']();
 break;
case 'b':
 cases['b']();
 break;
case 'c':
 cases['c']();
 break;
case 'd':
 cases['d']();
 break;
case 'e':
 cases['e']();
 break;
case 'f':
 cases['f']();
 break;
case 'g':
 cases['g']();
 break;
case 'h':
 cases['h']();
 break;
case 'i':
 cases['i']();
 break;
case 'j':
 cases['j']();
 break;
default:
}
pending…
Hash
if (typeof cases[theVar] == 'function') {
 cases[theVar]();
} else {

}
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