Why is Boolean() so slow in Javascript?
boolean, javascript, performance
Solution
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
Problem
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.