Effective ActionScript: Iteration

Flash, ActionScript, Front-End Programming — Matas Petrikas on March 27, 2007 at 3:12 pm
This post was inspired by Volodja Kolesnikovs article about non-trivial syntax in JavaScript. ActionScript and JS are both ECMA languages, which is why these ideas could be aplied to AS programming too. Take for example a “for” loop iteration. Here is a very usual example:
for(var i = 0; i < array.length; i++){
// here comes iteration code
}
The problem is, it calls the array length every cycle, thus wasting CPU resources. A better soulution would be:
var arrLength:Number = array.length;
for(var i = 0; i < arrLength; i++){
// here comes iteration code
}
We’ve called array.length just once here, but also we’ve created a variable, which has probably no use outside of iteration loop. The prettier and more effective solution would be:
 
for (var i = 0, l = myArr.length; i < l; i++) {
// here comes iteration code
}
We’ve saved some CPU cycles, and packed all iteration code in one compact piece. I’ve rewritten Volodjas test script in AS so you could check it for yourself. It looks, that you can save up to 60-70% CPU cycles using the effective method. iteration_test.as
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | Matas Ideas and Thoughts