简体   繁体   English

为什么 Boolean() 在 Javascript 中这么慢?

[英]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.根据 ECMAScript 规范,一元逻辑 NOT 运算符( ! ) 和Boolean()函数都使用内部函数ToBoolean() ,NOT 运算符也执行一些检查以反转结果。 So why is a double logical NOT operation much faster than running the Boolean() function?那么为什么双重逻辑 NOT 运算比运行Boolean()函数快得多呢?

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.注意:我指的不是new Boolean()构造函数,而是Boolean()函数,它强制将其提供给布尔值的参数。

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).虽然Boolean将调用该函数(内部优化),但大多数 JIT 将内联 double 而不使用 XOR,这要快得多( 源代码参考- JägerMonkey)。

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

I don't know how Javascript JIT compiler executed internally.我不知道 Javascript JIT 编译器是如何在内部执行的。 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 !!现在布尔函数在 2020 年在 Chrome 中运行得更快。但是如果有一些不同的浏览器,不同的版本或不同的 JS 引擎!! 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)当您使用! (NOT operator) ! (NOT operator) there is no need to create extra work inside memory for push/pop stack. ! (NOT operator)无需在内存中为推送/弹出堆栈创建额外的工作。 That is why NOT operator works faster.这就是 NOT 运算符工作得更快的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM