switch vs if-else

JavaScript performance comparison

Revision 20 of this test case created by Christian

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var type = typeof 1;
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
switch
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;
}
 
pending…
else-if
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';
}

 
pending…
and
type === 'boolean' && (r = 'boolean');
type === 'function' && (r = 'function');
type === 'object' && (r = 'object');
type === 'string' && (r = 'string');
type === 'number' && (r = 'number');
pending…
if
if (type === 'boolean') {
  r = 'boolean';
}
if (type === 'function') {
  r = 'function';
}
if (type === 'object') {
  r = 'object';
}
if (type === 'string') {
  r = 'string';
}
if (type === 'number') {
  r = 'number';
}
 
pending…
else-if non strict comparison
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';
}
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. Here’s a list of current revisions for this page:

1 comment

PVH commented :

Most interesting change from FF17 to FF18. The Switch performance is increased 400%!

Add a comment