Dlean Jeans
Dlean Jeans

Reputation: 996

Is there any difference in performance between these two for loop?

As I said: Is there any difference (in performance) between these two for loop? Between this:

    var n:int = displayObjects_.length;
    for (var i:int = 0; i < n; i++)
    {
        var currentObject:DisplayObject = displayObjects_[i];
        currentObject.width = newWidth;
    }

and this:

    var n:int = displayObjects_.length;
    for (var i:int = 0; i < n; i++)
    {
        displayObjects_[i].width = newWidth;
    }

I tested them before. The result said the first one was faster but I don't know if I did it right.

Upvotes: 1

Views: 60

Answers (3)

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

I tried this out on a bare-bones project using SDK 4.6. This is the code.

public class Main extends Sprite 
{

    public function Main() 
    {
        var displayObjects_:Array = [];
        for (var i:int = 0; i < 1000000; i++)
        {
            displayObjects_.push(new Sprite());
        }

        var start:int = getTimer();
        for (i = 0; i < displayObjects_.length; i++)
        {
            var currentObject:Sprite = displayObjects_[i];
            currentObject.width = 100;
        }
        var end:int = getTimer()
        trace(end, start, end - start);

        start = getTimer();
        for (i = 0; i < displayObjects_.length; i++)
        {
            displayObjects_[i].width = 100;
        }
        end = getTimer()
        trace(end, start, end - start);
    }
}

These are the results.

Done(0)
[Starting debug session with FDB]
16703 16250 453
17141 16703 438

Like I said, it would be very surprising to see any difference between the two. You'll probably see more improvements through using Vector instead of Array. Otherwise, this stuff is too mundane to fuss over.

Upvotes: 1

Selirion
Selirion

Reputation: 565

As I know, Actionscript compiler automatically moves variable definitions to the begin of the function. So, this loop doesn't declare variable each time, first sample the same that:

  var currentObject:DisplayObject;
  var n:int = displayObjects_.length;
    for (var i:int = 0; i < n; i++)
    {
        currentObject = displayObjects_[i];
        currentObject.width = newWidth;
    }

So, I think the difference only in one additional variable declare and it willn't affects performance. But 3vilguy's example is better.

Upvotes: 0

3vilguy
3vilguy

Reputation: 981

I know it's not really an answer to your question, but if you're looking for fastest way to iterate through this array you should do:

for each(var currentObject:DisplayObject in displayObjects_) {
    currentObject.width = newWidth;
}

Upvotes: 1

Related Questions