For VS Foreach on Array performance (in AS3/Flex)

2019-01-23 04:17发布

Which one is faster? Why?

var messages:Array = [.....]

// 1 - for
var len:int = messages.length;
for (var i:int = 0; i < len; i++) {
    var o:Object = messages[i];
    // ...
}

// 2 - foreach
for each (var o:Object in messages) {
    // ...
}

8条回答
神经病院院长
2楼-- · 2019-01-23 04:53

for would be faster for arrays...but depending on the situation it can be foreach that is best...see this .net benchmark test.

Personally, I'd use either until I got to the point where it became necessary for me to optimize the code. Premature optimization is wasteful :-)

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-23 04:54

I've had this discussion with a few collegues before, and we have all found different results for different scenarios. However, there was one test that I found quite eloquent for comparison's sake:

var array:Array=new Array();
for (var k:uint=0; k<1000000; k++) {
    array.push(Math.random());
}

stage.addEventListener("mouseDown",foreachloop);
stage.addEventListener("mouseUp",forloop);

/////// Array /////

/* 49ms */
function foreachloop(e) {
    var t1:uint=getTimer();
    var tmp:Number=0;
    var i:uint=0;
    for each (var n:Number in array) {
        i++;
        tmp+=n;
    }
    trace("foreach", i, tmp, getTimer() - t1);
}
/***** 81ms  ****/
function forloop(e) {
    var t1:uint=getTimer();
    var tmp:Number=0;
    var l:uint=array.length;
    for(var i:uint = 0; i < l; i++)
        tmp += Number(array[i]);
    trace("for", i, tmp, getTimer() - t1);
}

What I like about this tests is that you have a reference for both the key and value in each iteration of both loops (removing the key counter in the "for-each" loop is not that relevant). Also, it operates with Number, which is probably the most common loop that you will want to optimize that much. And most importantly, the winner is the "for-each", which is my favorite loop :P

Notes:

-Referencing the array in a local variable within the function of the "for-each" loop is irrelevant, but in the "for" loop you do get a speed bump (75ms instead of 105ms):

function forloop(e) {
    var t1:uint=getTimer();
    var tmp:Number=0;
    var a:Array=array;
    var l:uint=a.length;
    for(var i:uint = 0; i < l; i++)
        tmp += Number(a[i]);
    trace("for", i, tmp, getTimer() - t1);
}

-If you run the same tests with the Vector class, the results are a bit confusing :S

查看更多
叛逆
4楼-- · 2019-01-23 04:54

Just an add-on:

a for each...in loop doesn't assure You, that the elements in the array/vector gets enumerated in the ORDER THEY ARE STORED in them. (except XMLs) This IS a vital difference, IMO.

"...Therefore, you should not write code that depends on a for- each-in or for-in loop’s enumeration order unless you are processing XML data..." C.Moock

(i hope not to break law stating this one phrase...)

Happy benchmarking.

查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-23 05:00

Maybe in a array where all element are there and start at zero (0 to X) it would be faster to use a for loop. In all other case (sparse array) it can be a LOT faster to use for each. The reason is the usage of two data structure in the array: Hast table an Debse Array. Please read my Array analysis using Tamarin source: http://jpauclair.wordpress.com/2009/12/02/tamarin-part-i-as3-array/

The for loop will check at undefined index where the for each will skip those one jumping to next element in the HastTable

查看更多
▲ chillily
6楼-- · 2019-01-23 05:00

guys! Especially Juan Pablo Califano. I've checked your test. The main difference in obtain array item. If you will put var len : int = 40000;, you will see that 'while' cycle is faster. But it loses with big counts of array, instead for..each.

查看更多
贪生不怕死
7楼-- · 2019-01-23 05:03

From where I'm sitting, regular for loops are moderately faster than for each loops in the minimal case. Also, as with AS2 days, decrementing your way through a for loop generally provides a very minor improvement.

But really, any slight difference here will be dwarfed by the requirements of what you actually do inside the loop. You can find operations that will work faster or slower in either case. The real answer is that neither kind of loop can be meaningfully said to be faster than the other - you must profile your code as it appears in your application.

Sample code:

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

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

// for() reversed
time = getTimer();
for (i=size-1; 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");

Results:

for test: 124ms
for reversed test: 110ms
for each test: 261ms

Edit: To improve the comparison, I changed the inner loops so they do nothing but access the collection value.

Edit 2: Answers to oshyshko's comment:

  1. The compiler could skip the accesses in my internal loops, but it doesn't. The loops would exit two or three times faster if it was.
  2. The results change in the sample code you posted because in that version, the for loop now has an implicit type conversion. I left assignments out of my loops to avoid that. Of course one could argue that it's okay to have an extra cast in the for loop because "real code" would need it anyway, but to me that's just another way of saying "there's no general answer; which loop is faster depends on what you do inside your loop". Which is the answer I'm giving you. ;)
查看更多
登录 后发表回答