Switch vs. If + else

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

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

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