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

136 views Asked by At

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

There are 2 answers

4
Bergi On BEST ANSWER

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.

1
Siguza On

Because

val && "t" || "f"

has to evaluate val and, if val evaluates to true, "t" as well.

Using only false is therefore significantly faster than only true, but still quite slow.