9

According to the ECMAScript specification, both the unary logical NOT operator (!) and the Boolean() function use the internal function ToBoolean(), and the NOT operator also does a few checks to reverse the result. So why is a double logical NOT operation much faster than running the Boolean() function?

I used the following piece of code to test which was faster:

function logicalNotOperator() {
  var start = performance.now();
  for (var i = 0; i < 9999999; i++) !!Math.random();
  return 0.001 * (performance.now() - start);
}
 
function booleanFunc() {
  var start = performance.now();
  for (var i = 0; i < 9999999; i++) Boolean(Math.random());
  return 0.001 * (performance.now() - start);
}

var logicalNotOperatorResult = logicalNotOperator();
var booleanFuncResult = booleanFunc();
var diff = booleanFuncResult - logicalNotOperatorResult;

console.log('logicalNotOperator:', logicalNotOperatorResult);
console.log('booleanFunc:', booleanFuncResult);
console.log('diff:', diff);

Note: I am not referring to the new Boolean() constructor, but the Boolean() function that coerces the argument it's given to a boolean.

Valentin Podkamennyi
  • 7,161
  • 4
  • 29
  • 44
Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83

2 Answers2

7

While Boolean will call the function (internally optimized), most JITs will inline the double not to use XOR which is far faster (source code reference - JägerMonkey).

And the JSperf: http://jsperf.com/bool-vs-doublenot

Ven
  • 19,015
  • 2
  • 41
  • 61
  • 1
    I'd be interested in evidences on your `XOR` claim (this does not mean I don't believe you, I just like to know which source you got such information from). – Christoph Mar 11 '13 at 09:57
  • http://hg.mozilla.org/integration/mozilla-inbound/file/7c905a200bcc/js/src/methodjit/FastOps.cpp#l768 (that's for JägerMonkey - Spidmonkey's JavaScript methodjit) – Ven Mar 11 '13 at 10:06
  • Okay, interesting. Why are you using such a strange test setup. The overhead of two unrelated function calls seem to weaken the expressiveness of the test result. – Christoph Mar 11 '13 at 10:15
  • 2
    It's to avoid the JIT to optimize it all away, since it has no side effect. – Ven Mar 11 '13 at 10:15
  • 1
    They appear to be essentially equivalent (~1% difference) in Chrome 75. – Inkling Jul 19 '19 at 05:23
0

I don't know how Javascript JIT compiler executed internally. Also right now the Boolean function works faster in Chrome at 2020. But if there is some different browsers, different versions or different JS engines !! operator works faster I think I know the answer reason why. When you call a function there is extra work inside memory for push stack and pop stack. When you use ! (NOT operator) there is no need to create extra work inside memory for push/pop stack. That is why NOT operator works faster.

jeefo
  • 164
  • 1
  • 12