Is ternary operator, if-else or logical OR faster in javascript?
Which method is faster or more responsive in javascript, if-else, the ternary operator or logical OR? Which is advisable to use, for what reasons?
Seems like nobody did any actual profiling. Here's the code I used:
test = function() {
for (var i = 0; i < 10000000; i++) {
var a = i < 100 ? 1 : 2;
/*
if(i < 100) {
var a = 1;
}else{
var a = 2;
}
*/
}
}
test();
Using the if
/else
block instead of the ternary operator yields a 1.5 - 2x performance increase in Google Chrome v21 under OS X Snow Leopard.
As one use case where this is very important, synthesizing real-time audio is becoming more and more common with JavaScript. This type of performance difference is a big deal when an algorithm is running 44100 times a second.
I didn't think @charlie robert's test was fair
Here's my jsperf
result:
- strict equal is the fastest
- strict ternary is 33% slower
- truthy falsy is 49% slower
- ternary truthy falsy is 55% slower
- if else and ternary are roughly the same.
normal equal and normal ternary slowest.
strict equals:
var a = true, b;
if (a === true) {
b = true;
} else {
b = false
}
if (a === false) {
b = true;
} else {
b = false;
}
ternary strict equals
var a = true, b;
b = (a === true) ? true : false;
b = (a === false) ? true : false;
simple equality
var a = true, b;
if (a == true) {
b = true;
} else {
b = false;
}
if (a == false) {
b = true;
} else {
b = false;
}
simple ternary equality
var a = true, b;
b = (a == true) ? true : false;
b = (a == false) ? true : false;
truthy / falsy
var a = true, b;
if (a) {
b = true;
} else {
b = false;
}
if (!a) {
b = true;
} else {
b = false;
}
ternary truthy / falsy
var a = true, b;
b = (a) ? true : false;
b = (!a) ? true : false;
The speed difference will be negligible - use whichever you find to be more readable. In other words I highly doubt that a bottleneck in your code will be due to using the wrong conditional construct.
to charlie roberts' answer above, I would add:
the following link gives some incisive answers; the result for switches in Firefox being the most striking: http://jsperf.com/if-else-vs-arrays-vs-switch-vs-ternary/39
Those who question why anyone would investigate optimization to this degree would do well to research WebGL!
Ternary operator is only syntactic sugar, not a performance booster.