Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Boolean() so slow in Javascript?

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.

like image 623
Qantas 94 Heavy Avatar asked Mar 11 '13 09:03

Qantas 94 Heavy


People also ask

Which is faster == or === in JS?

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

Does JavaScript support boolean?

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.

What does boolean do in JavaScript?

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.

How check boolean value in if conditions in typescript?

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.


1 Answers

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

like image 126
Ven Avatar answered Oct 12 '22 01:10

Ven