根据 ECMAScript 规范,一元逻辑 NOT 运算符( !
) 和函数Boolean()
都使用内部函数ToBoolean()
,并且 NOT 运算符还进行一些检查以反转结果。那么为什么双逻辑非运算比运行函数快得多呢?Boolean()
我使用以下代码来测试哪个更快:
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);
注意:我指的不是new Boolean()
构造函数,而是Boolean()
强制将其赋予布尔值的参数的函数。