将参数添加到'自变量'类数组对象,性能测试

Add argument to 'arguments' array-like object, performance test

本文关键字:数组 对象 性能测试 自变量 添加 参数      更新时间:2023-09-26

你好,我做了一些简单的测试:在javascript:中向参数数组添加参数的更好方法

这表明使用Array.prototype.push.call大约慢3倍(chrome),为什么?

http://jsfiddle.net/vhrs56nm/

function test() {
    Array.prototype.push.call(arguments, 123);
}
function test2() {
    arguments[arguments.length] = 123;
    arguments.length++;
}
console.time("test1");
for ( var i=0; i<1000000; i++ ) {
    test(1,2,3);
}
console.timeEnd("test1");
console.time("test2");
for ( var i=0; i<1000000; i++ ) {
    test2(1,2,3);
}
console.timeEnd("test2");

Array.prototype.push.call大约慢3倍(chrome),为什么?

因为

  • 这是一个函数调用(实际上是两个),而且这些调用仍然需要一些代价
  • 传递arguments需要对象的具体化,这会扼杀优化
  • 执行死代码消除更为复杂