Why is the logical expression twice slower than if-else or inline-if-else?
function logicalExp(val) {
return val && "t" || "f";
}
function inlineIfElse(val) {
return val ? "t" : "f";
}
function ifElse(val) {
if (val) return "t";
else return "f";
}
- All functions evaluate with same results.
- All functions are being passed a value from an array of
1and0, see this jsperf test.
Because it does need to evaluate whether
"t"is truthy or not. The short-circuit expressionreturn ((val && "t") || "f")can be expanded toOf course, an optimising compiler could statically determine the truthiness of the
"t"literal, and avoid doingToBoolean(val)twice, but apparently this is not done in any JS engine.