[AS3] Let’s LOOP FOR a WHILE, a short performance comparison over loops in Actionscript 3
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.
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:
private function f1():void
{
var i:int = 0;
var n:int = int.MAX_VALUE/8;
for( i = 0; i < n; 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?
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.
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:
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.
Tags: comparison, counter, fast, for, int, iterations, Joa Ebert, loop, Number, performance, slow, uint, while



firstrow RIA e.U.
Excellent walk through, thank you for sharing.