Ternary vs Switch vs If (v8)

Revision 8 of this benchmark created by Josh on


Description

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

Setup

var a = Math.floor(Math.random() * 4),
        t;

Teardown


    a = Math.floor(Math.random() * 4);
  

Test runner

Ready to run.

Testing in
TestOps/sec
Ternary
t = (a === 1 ) ? 1 : (a === 2) ? 2 : 3;
ready
Switch
switch (a) {
case 1:
  t = 1;
  break;
case 2:
  t = 2;
  break;
case 3:
  t = 3;
  break;
}
ready
If
if (a === 1) t = 1;
if (a === 2) t = 2;
if (a === 3) t = 3;
ready
if else if
if (a === 1){
 t = 1;
}else if (a === 2){
 t = 2;
}else if (a === 3){
 t = 3;
}
ready
if else if else
if (a === 1){
 t = 1;
}else if (a === 2){
 t = 2;
}else{ 
t = 3;
}
ready
Ternary Separate
t = (a === 1) ? 1 : t;
t = (a === 2) ? 2 : t;
t = (a === 3) ? 3 : t;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.