2

这个问题真的是双重的:

  1. for each遍历 Array 与for通过其元素的简单循环在性能方面如何比较?

  2. 循环是否保证顺序遍历?以下代码说是:

var sample_array:Array = [];
for (var i:uint = 0; i < 10000; i++) sample_array.push(i);
i = 0;
for each(var value:uint in sample_array) {
  sample_array[i++] = value;
}

trace('in order was:', check_in_order(sample_array));

function check_in_order(array:Array):Boolean
{
  for (var i:uint = 0, l:uint = array.length; i < l; ++i) {
    if (array[i] != i) return false;
  }

  return true;
}

但我听说其他(高级)工程师上下发誓,遍历并不总是按升序进行!这是真的?

4

3 回答 3

6

正如Jackson Dunstan所证明的,他比较了forfor each并且for in使用不同的集合(数组、向量等),性能排名是(从最快到最慢):

  1. for
  2. for each
  3. for in(极慢)

在所有情况下for都是最快的。特别是与数组或向量一起使用时,for具有压倒性的性能。这些是所有集合的数字(越小意味着越快):

杰克逊·邓斯坦的 Loop Speed Redux

于 2013-05-31T03:49:06.960 回答
1

这是阿德里安的固定帖子

var size:Number = 10000000;
var arr:Array = [];
var time:Number, o:Object, i:int;
// fill container
for (i = 0; i < size; i++) arr[i] = i;

// for i
time = getTimer();
for (i=0; i<arr.length; i++){ arr[i]; }
trace("for test: "+(getTimer()-time)+"ms");

// for i reversed
time = getTimer();
for (i=arr.length; i>0; i--) { arr[i]; }
trace("for reversed test: "+(getTimer()-time)+"ms");

// for each
time = getTimer();
for each(o in arr) { o; }
trace("for each test: "+(getTimer()-time)+"ms");

// Result
for test: 212ms
for reversed test: 26ms
for each test: 103ms
于 2021-12-10T12:22:55.410 回答
-1

请查看我的帖子Flex Array Performance: For vs. ForEach

一些代码

var size:Number = 10000000;
var arr:Array = [];
for (var i:int=0; i
var time:Number, o:Object;

// for()
time = getTimer();
for (i=0; i=0; i--) { arr[i]; }
trace("for reversed test: "+(getTimer()-time)+"ms");

// for..in
time = getTimer();
for each(o in arr) { o; }
trace("for each test: "+(getTimer()-time)+"ms");

结果

for test: 124ms
for reversed test: 110ms
for each test: 261ms
于 2013-04-10T09:13:06.747 回答