Is a hash faster than a Switch in JavaScript?

Is a hash faster than a Switch in JavaScript?

 

simple performance test on jsperf.com and got these results:

Browser Switch ops/sec Hash table ops/sec % Difference
Chrome 6.0.490.1 dev 34,606,469 43,329,587 25% faster
Safari 5.0 16,777,216 10,854,824 35% slower
Opera 10.61 4,405,782 2,719,336 38% slower
Firefox 3.6.3 2,785,802 2,400,586 14% slower
IE6 147,870 206,869 40% faster
IE7 144,735 191,179 32% faster
IE8 350,085 472,417 35% faster
Mobile Safari (iOS4 on iPhone 3GS) 668,053 416,366 37% slower
Android (2.2 on Nexus One) 605,693 864,591 42% faster

* Ops/sec = Operations per second. Higher is better
** Chrome, Safari, Opera, and Firefox were tested on Mac OSX 10.6.4 2.53GHz Intel Core i5. IE tests were run on Windows 7 64bit 2.4GHz Quad Core

var foo = 'c';

switch(foo) {
  case 'a':
  break;
  case 'b':
  break;
  case 'c':
  break;
  default:
}


---
var foo = 'c';
var cases = {};
cases['a'] = function() {
  alert('I am A!');
};
cases['b'] = function() {
  alert('I am B!');
};
cases['c'] = function() {
  alert('I am C!');
}

if(typeof cases[foo] == 'function') {
  // only executes if we've defined it above
  cases[foo]();  // I am C!
} else {
  // default (the fallthrough)
}




This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s