switch vs object literal vs module (v19)

Revision 19 of this benchmark created on


Preparation HTML

<script>

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

function SwitchByObject (obj) {
        return function(that){
                return obj[that] || false;
        }
}

var switchByObj = new SwitchByObject({
        foo: noop,
        bar: noop,
        steins: noop,
        gate: noop,
        mad: noop,
        scientist: noop,
        alpha: alpha
});


  // 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();
};

</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

Revisions

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