3

在第一个示例中,我创建了长度为 1000 的空数组:

var arr = new Array(1000);

for (var i = 0; i < arr.length; i++)
  arr[i] = i;

在第二个示例中创建了长度为 0 的空数组:

var arr = [];

for (var i = 0; i < 1000; i++)
  arr.push(i);

在 OS X 10.10.3 上的 Chrome 41.0.2272.118 中进行测试,第一个块运行得更快。为什么?因为 JavaScript 引擎知道数组大小?

基准测试在这里http://jsperf.com/poerttest/2

4

3 回答 3

6

If you don't specify the array size it will have to keep allocating more space. But if you specify the size at the beginning, it only allocates once.

于 2015-04-12T07:27:37.743 回答
0

Yes. When you allocate size, interpreter knows that it has allocate only 1000 element memory/space. So, when you insert element, it is just one operation. But when you declare dynamic array, 2nd scenario your case, interpreter has to increase size of the array and then push the element. It is 2 operations!

于 2015-04-12T07:31:13.667 回答
0

另一种可能性可能push()是比分配到固定位置更昂贵。但测试表明情况并非如此。

发生的情况是空数组的起始容量相对较小(散列池或实际数组),并且增加该池的成本很高。Array(100)您可以通过尝试使用较小的尺寸来看到这一点:在 100 个元素时,两者之间的性能差异[]消失了。

于 2015-04-12T07:36:09.350 回答