在Javascript这么慢

在Javascript这么慢

本文介绍了为什么是布尔()在Javascript这么慢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据ECMAScript规范,既()和的使用的,而不是运营商也做了一些检查,以扭转结果。那么,为什么是双逻辑非操作中的布尔()功能?

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?

我用下面这段code,以测试这是更快的:

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);
}

注意:我不是指新布尔()的构造,但布尔()功能,它可以强制将它交给一个布尔的说法。

Note: I am not referring to the new Boolean() constructor, but the Boolean() function that coerces the argument it's given to a boolean.

推荐答案

布尔将调用函数(内部优化),最即时编译器将内联双不使用XOR远远快(来源$ C ​​$ C参考 - JägerMonkey)

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

而JSperf:

这篇关于为什么是布尔()在Javascript这么慢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:12