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 05:08

When iterating over an array, for each loops are way faster in my tests.

var len:int = 1000000;
var i:int = 0;
var arr:Array = [];

while(i < len) {
    arr[i] = i;
    i++;
}

function forEachLoop():void {
    var t:Number = getTimer();
    var sum:Number = 0;
    for each(var num:Number in arr) {
        sum += num;
    }
    trace("forEachLoop :", (getTimer() - t));
}

function whileLoop():void {
    var t:Number = getTimer();
    var sum:Number = 0;
    var i:int = 0;
    while(i < len) {
        sum += arr[i] as Number;                
        i++;
    }
    trace("whileLoop :", (getTimer() - t));
}

forEachLoop();
whileLoop();

This gives:

forEachLoop : 87 whileLoop : 967

Here, probably most of while loop time is spent casting the array item to a Number. However, I consider it a fair comparison, since that's what you get in the for each loop.

My guess is that this difference has to do with the fact that, as mentioned, the as operator is relatively expensive and array access is also relatively slow. With a for each loop, both operations are handled natively, I think, as opossed to performed in Actionscript.

Note, however, that if type conversion actually takes place, the for each version is much slower and the while version if noticeably faster (though, still, for each beats while):

To test, change array initialization to this:

while(i < len) {
    arr[i] = i + "";
    i++;
}

And now the results are:

forEachLoop : 328 whileLoop : 366

forEachLoop : 324 whileLoop : 369

查看更多
Evening l夕情丶
3楼-- · 2019-01-23 05:10

sorry to prove you guys wrong, but for each is faster. even a lot. except, if you don't want to access the array values, but a) this does not make sense and b) this is not the case here.

as a result of this, i made a detailed post on my super new blog ... :D

greetz

back2dos

查看更多
登录 后发表回答