AS3:哪个更快,for循环还是forEach()数组函数?

时间:2011-10-04 09:07:33

标签: arrays actionscript-3 loops

我想知道AS3中哪个更快:

array.forEach( function(v:Object, ...args):void
{ ... } );

或者

var l:int = array.length;
for ( var i:int = 0; i < l; i++ ) { ... }

4 个答案:

答案 0 :(得分:6)

对于我:)

var array:Array = [];
for (var i:int=0; i < 100000; i++)
{
    array[i] = i;
}
var time:uint = getTimer();
array.forEach( function(v:Object, ...args):void
                { v = 1; } );
trace(getTimer()-time); //trace 85


time = getTimer();
var l:int = array.length;
for ( i = 0; i < l; i++ ) { array[i] = 0; }
trace(getTimer()-time); //trace 3

答案 1 :(得分:3)

上述答案没有考虑到你将主要对循环中的数组元素执行操作

此代码

import flash.utils.getTimer;

var a:Array=[];
var time:int=0;

for(var i:int=0; i<10000; i++) {
    a.push(new Date());
}

time=getTimer();
for(var j:int=0; j<a.length; j++) {
    var dt:Date=a[j];
    dt.valueOf();
}
trace("for: " , getTimer()-time);

time=getTimer();
for each(var xt:Date in a) {
    xt.valueOf();
}
trace("for each: " , getTimer()-time);

time=getTimer();
a.forEach(nothing);
trace("a.forEach: " , getTimer()-time);

function nothing(d:Date, ...args):void {
    d.valueOf();
}

返回以下内容:

for:  3
for each:  2
a.forEach:  13

对于100000个值,结果仍然很明显

for:  27
for each:  17
a.forEach:  138

总冠军:每个循环

for each(var d:myClass in myCollection) {
    //myCode
}

答案 2 :(得分:1)

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

希望这有助于您理解for和for-each循环之间的区别。

答案 3 :(得分:1)

        var time:uint;
        var vec:Vector.<Number> = new Vector.<Number>;
        for (var b:int=0; b < 1000000; b++)
        {
            vec[b] = 99;
        }

        ///

        time = getTimer();
        for (var i:int = 0; i < vec.length; i++ )
        {
            vec[i] = 2;
        }
        trace('for i: '+(getTimer()-time)+'ms');

        ///

        time = getTimer();          
        for (var j:int = vec.length - 1; j >= 0; --j) 
        {
            vec[j] = 3;
        }
        trace('for i rev: '+(getTimer()-time)+'ms');            

        ///

        time = getTimer();
        for ( var k:int in vec)
        {
            vec[k] = 4;
        }
        trace('for: '+(getTimer()-time)+'ms');          

        ///

        time = getTimer();
        for each(var o:Number in vec)
        {
            o = 5;
        }
        trace('for each: '+(getTimer()-time)+'ms');         

        ///

        time = getTimer();
        vec.forEach( function(v:int, ...args):void
        {
            v = 6;
        }
        );
        trace('forEach: '+(getTimer()-time)+'ms');  

// for i: 81ms
// for i rev: 79ms
// for: 28ms
// for each: 33ms
// forEach: 530ms