javascript V8优化和“泄漏参数” [英] javascript V8 optimisation and "leaking arguments"

查看:55
本文介绍了javascript V8优化和“泄漏参数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在各个地方建议小心使用参数对象,这是可以的......

I read in various places that it's advisable to be careful with the arguments object and that this is ok...

    var i = arguments.length, args = new Array(i);
    while (i--) args[i] = arguments[i];

但是,这还好吗?...

But, is this ok or not?...

function makeArray (l) {
    var i = l.length, array = new Array(i);
    while (i--) array[i] = l[i];
    return array;
};
//...
//EDIT: put the function on an object to better represent the actual case
var o = {};
o.f = function (callback) {
    var args = makeArray (arguments);
    callback.apply(args[0] = this, args);
};

泄漏参数是什么意思?它如何影响优化?

What is meant by "leaking arguments" and how does it affect optimisation?

我专注于V8,但我认为它也适用于其他编译器?

I am focused on V8, but I assume it applies to other compilers as well?

证明它有效...

function makeArray (l) {
    var i = l.length, array = new Array(i);
    while (i--) array[i] = l[i];
    return array;
};
//...
//EDIT: put the function on an object to better represent the actual case
var o = {};
o.f = function (callback) {
    var args = makeArray (arguments);
    callback.apply(args[0] = this, args);
};
o.m = "Hello, ";
function test(f, n) {
    alert(this.m + " " + n)
}
o.f(test, "it works...")

推荐答案

参数的问题与本地 eval 相同,:它们会导致别名。 别名会破坏各种优化,所以即使您启用了这些功能的优化,也可能会结束只是浪费时间这是JIT的问题,因为在编译器中花费的时间不花时间运行代码(尽管优化管道中的一些步骤可以并行运行)。

The problem with arguments is same as with local eval and with: they cause aliasing. Aliasing defeats all sorts of optimizations so even if you enabled optimization of these kind of functions you would probably end up just wasting time which is a problem with JITs because the time spent in the compiler is time not spent running code (although some steps in the optimization pipeline can be run in parallel).

参数而导致的别名泄漏:

function bar(array) {    
    array[0] = 2;
}

function foo(a) {
    a = 1;
    bar(arguments);
    // logs 2 even though a is local variable assigned to 1
    console.log(a);
}
foo(1);

注意严格模式消除了这个:

Note that strict mode eliminates this:

function bar(array) {    
    array[0] = 2;
}

function foo(a) {
    "use strict";
    a = 1;
    bar(arguments);
    // logs 1 as it should
    console.log(a);
}
foo(1);

然而,严格模式也没有优化,我不知道任何合理的解释,除非基准测试没有不使用严格模式,很少使用严格模式。这可能会改变,因为许多es6功能需要严格模式,es6中不需要otoh 参数所以......

Strict mode however isn't optimized either and I don't know any reasonable explanation except that benchmarks don't use strict mode and strict mode is rarely used. That might change since many es6 features require strict mode, otoh arguments is not needed in es6 so...

这篇关于javascript V8优化和“泄漏参数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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