switch vs if-else (v7)

Revision 7 of this benchmark created by Aaron Zinman on


Setup

var type = typeof 1;
    var r;
    var assigningFunctionHandlers = {
      "boolean": function() {
        r = 'boolean';
      },
      "function": function() {
        r = 'function';
      },
      "object": function() {
        r = 'object';
      },
      "string": function() {
        r = 'string';
      },
      "number": function() {
        r = 'number';
      }
    };
    
    var returningFunctionHandlers = {
      "boolean": function() {
        return 'boolean';
      },
      "function": function() {
        return 'function';
      },
      "object": function() {
        return r 'object';
      },
      "string": function() {
        return r 'string';
      },
      "number": function() {
        return r 'number';
      }
    };
    
    var stringDictionaryLookup = {
      "boolean": 'boolean',
      "function": 'function',
      "object": 'object',
      "string": 'string',
      "number": 'number'
    };

Test runner

Ready to run.

Testing in
TestOps/sec
switch with type shifting
switch (type) {
case 'boolean':
  r = 'boolean';
  break;
case 'function':
  r = 'function';
  break;
case 'object':
  r = 'object';
  break;
case 'string':
  r = 'string';
  break;
case 4:
  r = 4;
  break;
case 'number':
  r = 'number';
  break;
default:
  r = "default";
  break;
}
ready
else-if with type shifting
if (type === 'boolean') {
  r = 'boolean';
} else if (type === 'function') {
  r = 'function';
} else if (type === 'object') {
  r = 'object';
} else if (type === 'string') {
  r = 'string';
} else if (type === 4) {
  r = 4;
} else if (type === 'number') {
  r = 'number';
} else {
  r = "default"
}
ready
switch (strings only)
switch (type) {
case 'boolean':
  r = 'boolean';
  break;
case 'function':
  r = 'function';
  break;
case 'object':
  r = 'object';
  break;
case 'string':
  r = 'string';
  break;
case 'number':
  r = 'number';
  break;
}
ready
else if (string only)
if (type === 'boolean') {
  r = 'boolean';
} else if (type === 'function') {
  r = 'function';
} else if (type === 'object') {
  r = 'object';
} else if (type === 'string') {
  r = 'string';
} else if (type === 'number') {
  r = 'number';
}
ready
to the point
r = type;
ready
assigning dictionary lookup
assigningFunctionHandlers[type]();
ready
returning dictionary lookup
r = returningFunctionHandlers[type]();
ready
string dictionary lookup
r = stringDictionaryLookup[type];
ready

Revisions

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