Ternary vs Switch vs If

JavaScript performance comparison

Revision 8 of this test case created by Josh

Info

Testing which is faster, ternary, switch, if, if else if, or if else if else. (modified comparison operators to test for exact match ===)

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var a = Math.floor(Math.random() * 4),
        t;
};

Benchmark.prototype.teardown = function() {
    a = Math.floor(Math.random() * 4);
};
</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
Ternary
t = (a === 1 ) ? 1 : (a === 2) ? 2 : 3;
pending…
Switch
switch (a) {
case 1:
  t = 1;
  break;
case 2:
  t = 2;
  break;
case 3:
  t = 3;
  break;
}
pending…
If
if (a === 1) t = 1;
if (a === 2) t = 2;
if (a === 3) t = 3;
pending…
if else if
if (a === 1){
 t = 1;
}else if (a === 2){
 t = 2;
}else if (a === 3){
 t = 3;
}
pending…
if else if else
if (a === 1){
 t = 1;
}else if (a === 2){
 t = 2;
}else{
t = 3;
}
pending…
Ternary Separate
t = (a === 1) ? 1 : t;
t = (a === 2) ? 2 : t;
t = (a === 3) ? 3 : t;
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