为什么是布尔()在Javascript这么慢? [英] Why is Boolean() so slow in Javascript?

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

问题描述

根据ECMAScript规范,既一元逻辑NOT运营商)和的布尔()功能使用的内部函数 ToBoolean() ,而不是运营商也做了一些检查,以扭转结果。那么,为什么是双逻辑非操作比运行速度更快中的布尔()功能?

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远远快(<一个href=\"http://hg.mozilla.org/integration/mozilla-inbound/file/7c905a200bcc/js/src/methodjit/FastOps.cpp#l768\"相对=nofollow>来源$ 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: http://jsperf.com/bool-vs-doublenot

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆