if/else vs arrays vs switch vs ternary
JavaScript performance comparison
Info
checks performance of the many types of case iterators in javascript.
Preparation code
<script>
function Switch( x ) {
switch ( x ) {
case 1: return 10; break;
case 2: return 18448; break;
case 3: return 188888; break;
case 4: return 166; break;
case 5: return 1516; break;
case 6: return 11105; break;
case 7: return 1215; break;
case 8: return 1116; break;
}
}
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;
}
function objects(x){
var testObject = { 1: 10,2: 18448, 3: 188888, 4: 166, 5: 1516, 6: 11105, 7: 1215, 8:1116 };
return testObject[x];
}
function arrays(x){
var testArray = [10,18448,188888,166,1516,11105,1215,1116];
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;
}
</script>
<script>
Benchmark.prototype.setup = function() {
function Switch( x ) {
switch ( x ) {
case 1: return 10; break;
case 2: return 18448; break;
case 3: return 188888; break;
case 4: return 166; break;
case 5: return 1516; break;
case 6: return 11105; break;
case 7: return 1215; break;
case 8: return 1116; break;
}
}
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;
}
function objects(x){
var testObject = { 1: 10,2: 18448, 3: 188888, 4: 166, 5: 1516, 6: 11105, 7: 1215, 8:1116 };
return testObject[x];
}
function arrays(x){
var testArray = [10,18448,188888,166,1516,11105,1215,1116];
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;
}
};
</script>
Test runner
Warning! For accurate results, please disable Firebug before running the tests. (Why?)
Java applet disabled.
| Test | Ops/sec | |
|---|---|---|
switch |
|
pending… |
if else |
|
pending… |
indexed arrays |
|
pending… |
object |
|
pending… |
ternary |
|
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:
- Revision 1: published by Adam Siegel
- Revision 2: published
- Revision 3: published
- Revision 4: published
- Revision 5: published
- Revision 6: published by pixel4
- Revision 18: published
- Revision 19: published
1 comment
Chrome so slow?