Search code examples
javascriptperformancejsperf

Why is `exp && "t" || "f"` much slower than inline-if-else?


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 1 and 0, see this jsperf test.

Solution

  • 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.