Switch vs Hash vs Others (v42)

Revision 42 of this benchmark created by Chris on


Preparation HTML

<script>
  var foo = -1000;
var cases = new Array(22);
var ch = "a".charCodeAt(0);
for(var i = 0; i <= 21; i++) {
  cases[String.fromCharCode(ch + i)] = new Function("foo+=" + i);
}
window.strthing = "";
</script>

Setup

var actions = cases;
  
  var doSwitch = function(str) {
  switch (str) {
    case "a":
      foo+=0;
      break;
    case "b":
      foo+=1;
      break;
    case "c":
      foo+=2;
      break;
    case "d":
      foo+=3;
      break;
    case "e":
      foo+=4;
      break;
    case "f":
      foo+=5;
      break;
    case "g":
      foo+=6;
      break;
    case "h":
      foo+=7;
      break;
    case "i":
      foo+=8;
      break;
    case "j":
      foo+=9;
      break;
    case "k":
      foo+=10;
      break;
    case "l":
      foo+=11;
      break;
    case "m":
      foo+=12;
      break;
    case "n":
      foo+=13;
      break;
    case "o":
      foo+=14;
      break;
    case "p":
      foo+=15;
      break;
    case "q":
      foo+=16;
      break;
    case "r":
      foo+=17;
      break;
    case "s":
      foo+=18;
      break;
    case "t":
      foo+=19;
      break;
    case "u":
      foo+=20;
      break;
    case "v":
      foo+=21;
      break;
  };
  if(foo > 1000) {window.strthing=foo;foo=foo%10;} /* just to make sure we don't get optimized away */
  };
  var doHash = function(str) {
  actions[str]();
  if(foo > 1000) {window.strthing=foo;foo=foo%10;} /* just to make sure we don't get optimized away */
  };

Test runner

Ready to run.

Testing in
TestOps/sec
Switch
var index = ~~(Math.random() * 22);
var chr = "a".charCodeAt(0);
var str = String.fromCharCode(chr + index);
doSwitch(str);
ready
Hash
var index = ~~(Math.random() * 22);
var chr = "a".charCodeAt(0);
var str = String.fromCharCode(chr + index);
doHash(str);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.