switch vs object literal vs module (v15)

Revision 15 of this benchmark created by ! on


Preparation HTML

<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

Ready to run.

Testing in
TestOps/sec
switch: hit
switchBySwitch('alpha')
ready
switch: miss
switchBySwitch('beta')
ready
switchObj: hit
switchByObj('alpha')
ready
switchObj: miss
switchByObj('beta')
ready
if-else: hit
switchByIfElse('alpha')
ready
if-else: miss
switchByIfElse('beta')
ready
if-return: hit
switchByIfReturn('alpha')
ready
if-return: miss
switchByIfReturn('beta')
ready
if-combined-return: hit
switchByCombinedIf('alpha')
ready
if-combined-return: miss
switchByCombinedIf('beta')
ready

Revisions

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