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";
}
1
and 0
, see this jsperf test.Because it does need to evaluate whether "t"
is truthy or not. The short-circuit expression return ((val && "t") || "f")
can be expanded to
var and = val ? "t" : val;
var or = and ? and : "f";
return or;
Of course, an optimising compiler could statically determine the truthiness of the "t"
literal, and avoid doing ToBoolean(val)
twice, but apparently this is not done in any JS engine.