switch vs object literal vs module

JavaScript performance comparison

Revision 15 of this test case created by !

Preparation code

<script>

var alpha = function(){ return true };
var defaultFunc = function(){ return false };

var switchByObj = (function(){
  var noop = function(){},
    switchObj = {
      foo: noop,
      bar: noop,
      steins: noop,
      gate: noop,
      mad: noop,
      scientist: noop,
      alpha: alpha
    };
  var _default = defaultFunc;
  return function(arg){
    (switchObj[arg] || _default)();
  };
})();

  // called by switch 
var switchBySwitch = function(arg){
  switch (arg) {
  case 'foo': break;
  case 'bar': break;
  case 'steins': break;
  case 'gate': break;
  case 'mad': break;
  case 'scientist': break;
  case 'alpha':
    alpha();
    break;
  default:
    defaultFunc();
  }
};
var switchByIfElse = function(arg){
  
  if(arg ==  'foo'){
  }
  else if(arg == 'bar'){
  }
  else if(arg == 'steins'){
  }
  else if(arg == 'gate'){
  }
  else if(arg == 'mad'){
  }
  else if(arg == 'scientist'){
  }
  else if(arg == 'alpha'){
    alpha();
  }
  else {
    defaultFunc();
  }
};

var switchByIfReturn = function(arg){
  
  if(arg ==  'foo'){
    return;
  }
  if(arg == 'bar'){
    return;
  }
  if(arg == 'steins'){
    return;
  }
  if(arg == 'gate'){
    return;
  }
  if(arg == 'mad'){
    return;
  }
  if(arg == 'scientist'){
    return;
  }
  if(arg == 'alpha'){
    return alpha();
  }
  return defaultFunc();
};
var switchByCombinedIf = function(arg){  
    if(arg ==  'foo' || arg == 'bar' || arg == 'steins' || arg == 'gate' || arg == 'mad' || arg == 'scientist'){
        return;
    } 
    if (arg == 'alpha'){
        return alpha();
    }
    return defaultFunc();
};

</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
switch: hit
switchBySwitch('alpha')
pending…
switch: miss
switchBySwitch('beta')
pending…
switchObj: hit
switchByObj('alpha')
pending…
switchObj: miss
switchByObj('beta')
pending…
if-else: hit
switchByIfElse('alpha')
pending…
if-else: miss
switchByIfElse('beta')
pending…
if-return: hit
switchByIfReturn('alpha')
pending…
if-return: miss
switchByIfReturn('beta')
pending…
if-combined-return: hit
switchByCombinedIf('alpha')
pending…
if-combined-return: miss
switchByCombinedIf('beta')
pending…

Compare results of other browsers

Revisions

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

0 Comments