`arguments`增加了运行时间(神秘地)

时间:2013-09-06 06:12:42

标签: javascript

我实现了一个简单的轻量级every函数。我注意到如果变量arguments以某种方式在函数内部使用 - 它 800 ms 的运行时间增加 1300 ms (在我的情况下)。是什么原因造成的?

我使用 Chrome 29.0.1547.66 m

http://jsfiddle.net/4znzy/

function myEvery(list, fun, withArgument) {
    var i;

    fun = fun || function(val) { return val };

    arguments; // with this statement the time is 1300 ms
               // if you comment it out -- 800 ms

    for (i = 0; i < list.length; i++) {
      if (!fun.call(list, list[i], i)) {
        return false;
      }
    }

    return true;
};

// Create a huge array
var list = [];
for (i = 1; i < 20000000; i++) {
    list.push(i);
}

// Measure the time
t1 = (new Date).getTime();
myEvery(list);
t2 = (new Date).getTime();

alert(t2 - t1);

(如果要测量执行arguments语句本身的时间,则为0 ms。)

1 个答案:

答案 0 :(得分:1)

arguments的外观就像是函数参数的动态getter,它必须从堆栈中读取 - 并被复制。像list参数这样的大型对象(不仅仅是大而且很多)也必须复制

您可以通过将<{1}}行替换为

来查看此内容
arguments

导致相似的时间。我的机器上额外150个var args = [list.slice(0)]; // copy parameter 和200个arguments

根据JS引擎的实现,这将更慢或更快,但肯定会增加执行时间。 可能(尚未经过测试)不同浏览器或其他JS引擎之间存在很大差异。