• Feedburner RSS
  • Comments RSS
  • Post RSS

Optimizing a For loop

April 17th, 2009

Alot of the time I spend developing flash, I’m always looking for ways to optimize my code and make it run faster. Take for instance the following code.

var arrStuff:Array = new Array();
arrStuff.push({label:"thing1"});
arrStuff.push({label:"thing2"});
 
for(var i:int=0; i<arrStuff.length; i++){
 
}

Should be written like so

var arrStuff:Array = new Array();
arrStuff.push({label:"thing1"});
arrStuff.push({label:"thing2"});
var numLen:int = arrStuff.length;
for(var i:int=0; i<numLen; i++){
 
}

The reasoning for this is because it’s less work for flash to do. Instead of every single loop looking up the array’s length, it simply just compares it to a number (or int). It may not seem like much a difference, but later if your looping through thousands of objects it could definitely help.

2 Responses to “Optimizing a For loop”

If using this code optimization, make sure that no other process within has access to alter the number of items within the array. If another process alters the length of the array by adding or removing an item, it could cause the process within the iterative to throw an exception. Code optimization is a balancing act that requires much attention to detail so you don’t end up with random bugs you have a hard time finding or reproducing.

I’m not sure how the Flash Array class is implemented but if it’s significantly slower to use Array.length then it might make more sense to implement your own array class that extends the Flash array class and adds a single property similar to length which is incremented or decremented when push, pop, join, etc calls are made. Just a thought.

Normally if this was in a class, it’d be a local variable inside of a function and once the functions complete it’ll cease to exist.

It don’t think it’s significantly slower but imagining many multidimensional arrays looping on an interval (such as collision testing)…. it should help a little.

I believe that’s basically what the array already does, considering that “length” is the property being incremented/decremented. I’m simply saying instead of accessing an objects property over and over, it should help to make a local variable within your function for each loop.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">