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.
So === faster than == in Javascript === compares if the values and the types are the same. == compares if the values are the same, but it also does type conversions in the comparison. Those type conversions make == slower than ===.
Boolean is a datatype that returns either of two values i.e. true or false. In JavaScript, Boolean is used as a function to get the value of a variable, object, conditions, expressions, etc. in terms of true or false.
In JavaScript, a boolean value is one that can either be TRUE or FALSE. If you need to know “yes” or “no” about something, then you would want to use the boolean function. It sounds extremely simple, but booleans are used all the time in JavaScript programming, and they are extremely useful.
Use the typeof operator to check if a value is of boolean type, e.g. if (typeof variable === 'boolean') . The typeof operator returns a string that indicates the type of a value. If the value is a boolean, the string "boolean" is returned.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With