Optimized Switch vs If/Else

JavaScript performance comparison

Test case created by Josh

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var counter = 0;
  
  function switchTest(value){
      var returnValue = undefined;
      switch(value){
          case 0: 
            returnValue = '0'
            counter++
            break;
          case 1: 
            returnValue = '1'
            counter++
            break;
          case 2: 
            returnValue = '2'
            counter++
            break;
          case 3: 
            returnValue = '3'
            counter++
            break;
          case 4: 
            returnValue = '4'
            counter++
            break;
          case 5: 
            returnValue = '5'
            counter++
            break;
          case 6: 
            returnValue = '6'
            counter++
            break;
          case 7: 
            returnValue = '7'
            counter = 0;
            break;
      }
  
      return returnValue;
  }
  
  function ifElseTest(value){
      var returnValue = undefined;
  
      if(value == 0) {
          returnVaue = '0';
          counter++;
      }
      else if(value == 1) {
          returnValue = '1';
          counter++;
      }
      else if(value == 2) {
          returnValue = '2';
          counter++;
      }
      else if(value == 3) {
        returnValue = '3';
        counter++;
      }
      else if(value == 4) {
        returnValue = '4';
        counter++;
      }
      else if(value == 5) {
        returnValue = '5';
        counter++;
      }
      else if(value == 6) {
         returnValue = '6';
         counter++;
      }    
      else if(value == 7) {
          returnValue = '7';
          counter = 0;
      }
  }

};

Benchmark.prototype.teardown = function() {
  counter = 0;

};
</script>

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
switchTest
switchTest(counter);
pending…
ifElseTest
ifElseTest(counter);
pending…

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

Compare results of other browsers

0 Comments