if/else vs switch vs lookup

JavaScript performance comparison

Test case created by alejalapeno

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const colorCodes = {
      'blue'   : '#2196F3',
      'green'  : '#4CAF50',
      'orange' : '#FF9800',
      'pink'   : '#E91E63',
      'default': '#F44336'
  };
  
  const setBackgroundColorIf = (colorName) => {
      let colorCode = '';
      if(colorName === 'blue') {
          colorCode = '#2196F3';
      } else if(colorName === 'green') {
          colorCode = '#4CAF50';
      } else if(colorName === 'orange') {
          colorCode = '#FF9800';
      } else if(colorName === 'pink') {
          colorCode = '#E91E63';
      } else {
          colorCode = '#F44336';
      };
      document.body.style.backgroundColor = colorCode;
  };
  
  const setBackgroundColorSwitch = (colorName) => {
      let colorCode = '';
      switch(colorName) {
          case 'blue':
              colorCode = '#2196F3';
              break;
          case 'green':
              colorCode = '#4CAF50';
              break;
          case 'orange':
              colorCode = '#FF9800';
              break;
          case 'pink':
              colorCode = '#E91E63';
              break;
          default:
              colorCode = '#f44336';
      };
      document.body.style.backgroundColor = colorCode;
  };
  
  const setBackgroundColorLookup = (colorName) => {
      document.body.style.backgroundColor = colorCodes[colorName] || colorCodes['default'];
  };

};
</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
if/else
setBackgroundColorIf('yellow');
setBackgroundColorIf('blue');
setBackgroundColorIf('red');
setBackgroundColorLookup('purple');
pending…
Switch
setBackgroundColorSwitch('yellow');
setBackgroundColorSwitch('blue');
setBackgroundColorSwitch('red');
setBackgroundColorLookup('purple');
pending…
Lookup Table
setBackgroundColorLookup('yellow');
setBackgroundColorLookup('blue');
setBackgroundColorLookup('red');
setBackgroundColorLookup('purple');
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