我尝试了下一个代码(它在Google Chrome和nodejs中显示相似的结果):

var t = new Array(200000); console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 27839.499ms
undefined

我还运行了下一个测试:
var t = []; console.time('wtf'); for (var i = 0; i < 400000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 449.948ms
undefined
var t = []; console.time('wtf'); for (var i = 0; i < 400000; ++i) {t.push(undefined);} console.timeEnd('wtf');
wtf: 406.710ms
undefined

但是在Firefox中,第一个变体看起来一切正常:
>>> var t = new Array(200000); console.time('wtf'); ...{t.push(Math.random());} console.timeEnd('wtf');
wtf: 602ms

V8中会发生什么?

UPD
*神奇地降低性能*
var t = new Array(99999); console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 220.936ms
undefined
var t = new Array(100000); t[99999] = 1; console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 1731.641ms
undefined
var t = new Array(100001); console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 1703.336ms
undefined
var t = new Array(180000); console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 1725.107ms
undefined
var t = new Array(181000); console.time('wtf'); for (var i = 0; i < 200000; ++i) {t.push(Math.random());} console.timeEnd('wtf');
wtf: 27587.669ms
undefined

最佳答案

如果进行预分配,请不要使用.push,因为您将创建一个由哈希表支持的稀疏数组。 You can preallocate sparse arrays up to 99999 elements将由C数组支持,此后为哈希表。

使用第二个数组,您将以连续的方式从0开始添加元素,因此它将由真实的C数组(而不是哈希表)支持。

大致来说:

如果您的数组索引从0到Length-1很好,没有孔,则可以用快速C数组表示。如果你有
数组中的空洞,那么它将由一个慢得多的哈希表表示。异常(exception)是,如果您预先分配了一个数组
大小小于100000,那么您可以在数组中有孔,但仍然得到C数组的支持:

var a = new Array(N);

//If N < 100000, this will not make the array a hashtable:
a[50000] = "sparse";

var b = [] //Or new Array(N), with N >= 100000
//B will be backed by hash table
b[50000] = "Sparse";
//b.push("Sparse"), roughly same as above if you used new Array with N > 0

09-25 16:46
查看更多