Ludicrous Software

Optimizing Loops

Here’s a quick optimization tip that can pay big dividends: If you can, try to avoid using functions as the condition of your for or while loops. For example, consider this code:

myString = "lorem ipsum lorem ipsum";
for (i = 1; i <= length(myString); i++) {
trace(substring(myString, i, 1));
}

Every time the Flash Lite player iterates through the loop, it evaluates length(myString) to see if i is less than or equal to the length of the string. However, because the length of myString is not changing, there’s no need to re-evaluate the length of the string with every iteration of the loop. Checking against a simple variable is faster, so you should use this code instead:

myString = "lorem ipsum lorem ipsum";
stringLength = length(myString);
for (i = 1; i <= stringLength; i++) {
trace(substring(myString, i, 1));
}

Because the conditional is a variable instead of a function, you save some CPU time. Depending on the number of iterations in your loop, this can really add up. And as you no doubt know if you’ve been doing Flash Lite development for any length of time, every little bit helps!

Of course, if the value of your condition is changing as a result of the code being executed in the loop, then you will have to use your function as the condition. But if that value is not changing, as in the example above, then this is a simple way to speed up your app.