if/else vs arrays vs switch vs ternary (v6)

Revision 6 of this benchmark created by pixel4 on


Description

checks performance of the many types of case iterators in javascript.

Setup

function Switch( x ) {
            switch ( x ) {
                    case 1: return 10;
                    case 2: return 18448;
                    case 3: return 188888;
                    case 4: return 166;
                    case 5: return 1516;
                    case 6: return 11105;
                    case 7: return 1215;
                    case 8: return 1116;
            }       
    }
    
    function elseIf( x ) {
            if ( x === 1 ) return 10;
            else if ( x === 2 ) return 18448;
            else if ( x === 3 ) return 188888;
            else if ( x === 4 ) return 166;
            else if ( x === 5 ) return 1516;
            else if ( x === 6 ) return 11105;
            else if ( x === 7 ) return 1215;
            else if ( x === 8 ) return 1116;
    }
    
    var testObject = { 1: 10,2: 18448, 3: 188888, 4: 166, 5: 1516, 6: 11105, 7: 1215, 8:1116 };
    function objects(x){
            return testObject[x]; 
    }
    
    var testArray = [10,18448,188888,166,1516,11105,1215,1116];
    function arrays(x){        
            return testArray[x-1];
    }
    
    function ternary(x){
           var output = x==1?10:x==2?18448:x==3?188888:x==4?166:x==5?1516:x==6?11105:x==7?1215:x==8?1116:15;
           return output;
    }

Test runner

Ready to run.

Testing in
TestOps/sec
switch
Switch(1);
Switch(2);
Switch(3);
Switch(4);
Switch(5);
Switch(6);
Switch(7);
Switch(8);
ready
if else
elseIf(1);
elseIf(2);
elseIf(3);
elseIf(4);
elseIf(5);
elseIf(6);
elseIf(7);
elseIf(8);
ready
indexed arrays
arrays(1);
arrays(2);
arrays(3);
arrays(4);
arrays(5);
arrays(6);
arrays(7);
arrays(8);
ready
object
objects(1);
objects(2);
objects(3);
objects(4);
objects(5);
objects(6);
objects(7);
objects(8);
ready
ternary
ternary(1);
ternary(2);
ternary(3);
ternary(4);
ternary(5);
ternary(6);
ternary(7);
ternary(8);
ready

Revisions

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