我在 Chrome/Firefox 中测试了这段代码:
console.time('simple push');
var arr0 = [];
for(var i =0; i < 1000000; i++){
arr0.push(i);
}
console.timeEnd('simple push');
console.time('set length and push');
var arr1 = [];
arr1.length=1000000;
for(var j =0; j < 1000000; j++){
arr1[j]=j;
}
console.timeEnd('set length and push');
console.time('new Array push');
var arr2 = new Array(1000000);
for(var k =0; k < 1000000; k++){
arr2[k]=k;
}
console.timeEnd('new Array push');
Chrome 13 结果
简单推送:59ms
设置长度和推送:192ms
新数组推送:187ms
Firefox 4 结果
简单推送:76ms
设置长度和推送:44ms
新数组推送:40ms
我的疑问
所以 new Array
操作肯定是最慢的,但我想知道为什么?
为什么设置长度在 Chrome 和 Firefox 中表现不同,似乎预分配内存在 Chrome 中效果不佳?
更新
我更新了 Chrome 和 FF 结果。
最佳答案
为什么 new Array(N) 最慢?
console.log(arr0.length);
console.log(arr1.length);
console.log(arr2.length);
1000000
1000000
2000000
关于javascript - javascript数组在推送新元素时如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7151097/