Switch vs. If + else

JavaScript performance comparison

Test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var num = '50';
};

Benchmark.prototype.teardown = function() {
    num = null;
};
</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 (num) {
  case '10':
    console.log('You chose number:' + num);
    break;
  case '20':
    console.log('You chose number:' + num);
    break;
  case '30':
    console.log('You chose number:' + num);
    break;
  case '40':
    console.log('You chose number:' + num);
    break;
  case '50':
    console.log('You chose number:' + num);
    break;
  case '60':
    console.log('You chose number:' + num);
    break;
  case '70':
    console.log('You chose number:' + num);
    break;
  case '80':
    console.log('You chose number:' + num);
    break;
  case '90':
    console.log('You chose number:' + num);
    break;
  case '100':
    console.log('You chose number:' + num);
    break;
};
pending…
If/Else
if (num === '10') {
  console.log('You chose number:' + num);
} else if (num === '20') {
  console.log('You chose number:' + num);
} else if (num === '30') {
  console.log('You chose number:' + num);
} else if (num === '40') {
  console.log('You chose number:' + num);
} else if (num === '50') {
  console.log('You chose number:' + num);
} else if (num === '60') {
  console.log('You chose number:' + num);
} else if (num === '70') {
  console.log('You chose number:' + num);
} else if (num === '80') {
  console.log('You chose number:' + num);
} else if (num === '90') {
  console.log('You chose number:' + num);
} else if (num === '100') {
  console.log('You chose number:' + num);
};
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:

0 comments

Add a comment