Looking at the world of media: from music to RIA.

AS3 Performance: For Loops

October 26th, 2007 Posted in ActionScript, Flash Player, Rich Internet Applications

rune_flash.gifA while back I was reading an article on Ajaxian (I can’t remember who wrote it) but it was talking about JavaScript performance tips. One of them was around writing blazing fast For loops and for some reason it really stuck in my head. The trick the author recommended was that when running a For loop don’t use a method in the loop test expression but use a scalar value. The idea is that if you are making a method call, such as length(), in the test expression this takes more processing time to calculate the method then just applying the scalar value.

If you followed me, bravo, if not… here is an example that will make a lot more sense. Let’s say that you want to loop over an Array. The typical For loop looks like this (note: the syntax highlighter is ignoring the < and replacing it with the HTML character):

var myArray:Array = new Array();
... // populate the array
for(var i:uint; i < myArray.length; i++)
{
	... // do something
}

Pretty standard stuff. The issue with this method is that every time we enter the loop we call myArray.length to validate if we should run the code or end the loop. This means that a get method is being called to validate the Array length and then return it. By adding one line of code we can remove this call and see better performance:

var myArray:Array = new Array();
... // populate the array
var len:int = myArray.length;
for(var i:uint = 0; i < len; i++)
{
	... // do something
}

I wrote a test Flex app that demos both versions and using 100,000 loops (yeah, super brute force I know). I saw a significate performance increase. The first method took 24ms the second method took 13ms. So the next thing I did was change the Array to an ArrayCollection because this is more of a typical use case. More and more applications are pulling in large data sets and every ms counts. With an ArrayCollection the first method took 577 ms vs. 424 ms.

Its amazing to me that an extra line of code can help this much but at the same time it makes a lot of sense. I have uploaded the MXML file so that you all can play with it… so enjoy!

folder.png Speedtest.mxml [download]

You must be logged in to post a comment.