AS3 loops, performance comparison

October 8, 2006 on 6:20 pm | In Actionscript | 12 Comments

Recently I did some benchmarks to determine the fastest loop in AS3. Here are the result:

  performance decrease in percent
empty loop / variable assigment in body
loop code AS3 AS2
for (i = 0; i < k; i++) {} 0*/7 0/0
for (i = 0; i++ < k;) {} 35/0 0/3
i = 0; while (i < k) { i++; } 5/6 0/2
i = 0; while (i++ < k) {} 35/3 0/3
i = k; while (i-- > 0) {} 5/0 5/1
i = k; while (i--) {} 20/0 5/5
for (each in o) compared to fastest loop 2800 30
for each (i in o) compared to fastest loop 45 N/A

So the main thing to keep in mind is that a for..in loop is now roughly 28 times slower than a standard integer loop - in AS2 the impact wasn’t that big. Also don’t overload the loop header, but put everything in the loop body instead, for example:

// slower
var k:int = 1000;
for (var j:int = k - 1, i:int = 0; i < k; j = i, i++)
{
}

// faster
var k:int = 1000;
var j:int = k - 1;
for (var i:int = 0; i < k; i++)
{
    j = i;
}

Another importing thing is integer casting when accessing array elements:
The second example is roughly 20% faster than the first one:

// i*2 gets promoted to Number
for (var i:int = 0; i < 10000; i++)
{
    a[i*2] = 0;
}

// Goes through fast path
for (var i:int =0; i < 10000; i++)
{
    a[int(i*2)] = 1;
}

This was pointed out on slide 26 (”Promotion of Numeric Types”) in the paper
ActionScript 3.0 and AVM2: Performance Tuning by Gary Grossman.

Conclusion

So, in AS3 there isn’t really that much of a difference between the loop variations. The benchmark results were made by iterating an empty loop with 10.000.000 iterations. From this point of view, it doesn’t matter at all.

If you have many loops which only get or set values and do simple arithmetics, you will perhaps notice a difference. But you have to always look at the broader image and find the bottleneck of the application, and a loop is the last thing you would optimize at first place.

FlashDevelop 2.0.0 released

October 5, 2006 on 9:31 pm | In Links, Miscellaneous | No Comments

Finally, FlashDevelop 2 is released :-) No new features, but some bug fixes and improvements. One outstanding feature is the fast auto-completion for build-in and custom classes, which I never want to miss again. And it already supports AS3 and Flex2 compilation. If you have never used FlashDevelop, give it a try.

Proudly powered by WordPress Theme based upon Pool theme by Borja Fernandez.
Entries and comments feeds.