[AS3] Let’s LOOP FOR a WHILE, a short performance comparison over loops in Actionscript 3

by Bernd on July 22nd, 2009

Months ago someone pointed me at Joa Ebert’s wiki, which has a interesting category: Code Optimization. In this post I want to test some performance statements made in the loop article

I tested for and while loops with different data types (uint and int, Number is 4-5 times slower) and counting mechanisms (i++ or ++i), with and without accessing the counter variable. All loops had 268435455 (int.MAX_VALUE/8) iterations on my tripple core 2,1Ghz machine, 32bit WinXP, Flash player 10. The y-axis shows us the average time in milliseconds of at least 10 iterations. The highest and lowest value is not included.

AS3 Loop comparison

We can see that for is faster than while. Why? Well .. I just don’t know, if you have any idea, please leave a comment!

So the fasted two loops, nearly head to head, were:

//for uint i++
private function f1():void
{

var i:int = 0;

var n:int = int.MAX_VALUE/8;

for( i = 0; i < n; i++ ) { }

}

//for int ++i
private function f3():void
{

var i:int = 0;

var n:int = int.MAX_VALUE/8;

for( i = 0; i < n; ++i ) { }

}

 

Then I took a closer look on the for loops. Why is the ordinary loop with int as data type and i++ value increase slower?

AS3 for loops

 

What if the loop body is not empty and the value of the counter is needed? Well, here are the results. At this time 17895697 (int.MAX_VALUE/120) were enough.

AS3 for loops with access to counter var

Ok, now we are nearly at the same level, regardless of which data type or counting style is used. The only (negative) abnormality is the uint while, which is about 9% slower than the fastest loop.

Here we have the slow performer:

//while uint –n
private function f8():void
{

var i:uint = 0;

var n:uint = int.MAX_VALUE/120;

while( –n >= i )

{

n;

}

}

 

Conclusion: It’s totally up to you which loop you prefer (if you have to access the counter variable). For me I will continue to use the ordinary for loop, just like I ever did.

 

1 Comment
  1. Excellent walk through, thank you for sharing.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS