Switch vs Hash vs Others (v29)

Revision 29 of this benchmark created by JSench on


Setup

var index = 0;
  var foo = 0;
  var cached = {};
  
  function myFunction0() {
    foo++;
  }
  
  function myFunction1() {
    foo++;
  }
  
  function myFunction2() {
    foo++;
  }
  
  function myFunction3() {
    foo++;
  }
  
  function myFunction4() {
    foo++;
  }
  
  function myFunction5() {
    foo++;
  }
  
  function myFunction6() {
    foo++;
  }
  
  function myFunction7() {
    foo++;
  }
  
  function myFunction8() {
    foo++;
  }
  
  function myFunction9() {
    foo++;
  }
  
  var cases = [];
  cases[0] = myFunction0;
  cases[1] = myFunction1;
  cases[2] = myFunction2;
  cases[3] = myFunction3;
  cases[4] = myFunction4;
  cases[5] = myFunction5;
  cases[6] = myFunction6;
  cases[7] = myFunction7;
  cases[8] = myFunction8;
  cases[9] = myFunction9;

Test runner

Ready to run.

Testing in
TestOps/sec
Switch
for (index = 0; index < 10; index++) {
  switch (index) {
    case 0:
      myFunction0();
      break;
    case 1:
      myFunction1();
      break;
    case 2:
      myFunction2();
      break;
    case 3:
      myFunction3();
      break;
    case 4:
      myFunction4();
      break;
    case 5:
      myFunction5();
      break;
    case 6:
      myFunction6();
      break;
    case 7:
      myFunction7();
      break;
    case 8:
      myFunction8();
      break;
    case 9:
      myFunction9();
      break;
  }
}
ready
Hash
for (index = 0; index < 10; index++) {
  cases[index]();
}
ready
Cached Hash
for (index = 0; index < 10; index++) {
  cached = cases[index];
  cached();
}
ready
If ===
for (index = 0; index < 10; index++) {
  if (index === 0) {
    myFunction0();
  } else if (index === 1) {
    myFunction1();
  } else if (index === 2) {
    myFunction2();
  } else if (index === 3) {
    myFunction3();
  } else if (index === 4) {
    myFunction4();
  } else if (index === 5) {
    myFunction5();
  } else if (index === 6) {
    myFunction6();
  } else if (index === 7) {
    myFunction7();
  } else if (index === 8) {
    myFunction8();
  } else if (index === 9) {
    myFunction9();
  }
}
ready
If ==
for (index = 0; index < 10; index++) {
  if (index == 0) {
    myFunction0();
  } else if (index == 1) {
    myFunction1();
  } else if (index == 2) {
    myFunction2();
  } else if (index == 3) {
    myFunction3();
  } else if (index == 4) {
    myFunction4();
  } else if (index == 5) {
    myFunction5();
  } else if (index == 6) {
    myFunction6();
  } else if (index == 7) {
    myFunction7();
  } else if (index == 8) {
    myFunction8();
  } else if (index == 9) {
    myFunction9();
  }
}
ready

Revisions

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