Switch vs. if/else

JavaScript performance comparison

Revision 2 of this test case created

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var str = ['a', 'b', 'c'][Math.floor(Math.random() * 3)];
    var i = 0;
    function a() {
      //console.log('a');
      i++;
    }
   
    function b() {
      //console.log('b');
      i++;
    }
   
    function c() {
      //console.log('c');
      i++;
    }
};
</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(str) {
  case 'a':
    a();
    break;
  case 'b':
    b();
    break;
  case 'c':
    c();
    break;
}
pending…
if/else
if (str === 'a') {
  a();
} else if (str === 'b') {
  b();
} else if (str === 'c') {
  c();
}
pending…
map
var map = {
  a: a,
  b: b,
  c: c
};

map[str]();
pending…
array
var arr = [a, b, c];
var x = 'abc';

arr[x.indexOf(str)]();
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