Avg. Rating 5.0

Problem

Using a function within the condition expression of a loop decreases runtime speed.

Solution

If possible, substitute the function within the condition expression with a variable.

Detailed explanation

Using a function call within the condition of a for or while loop can slow down your Flash Lite application because the function must be evaluated with every iteration. If possible, assign the value of the function to a variable and use the variable in your condition expression. For example, consider the following simple loop:
myString = "lorem ipsum lorem ipsum";
for (i = 1; i <= myString.length; i++) {
// do something here
}
Every time the code iterates through the loop, it must evaluate myString.length to see if it should continue executing the code in the loop. If myString.length remains static, then the following code will run faster:
myString = "lorem ipsum lorem ipsum";
sLength = myString.length
for (i = 1; i <= sLength; i++) {
// do something here
}
Keep these points in mind when considering whether to use this method to optimize your loop:
  1. This method may not be appropriate if the value of the condition changes as a result of the code inside the loop.  For example, if the code inside the for loop above truncated or added characters to myString, the value of myString.length would change. In this situation, not evaluating myString.length in the condition of the loop may produce unwanted results.
  2. The greater the number of iterations in your loop, the greater the total speed improvement. Inversely, this may not produce significant speed improvements if the number of iterations is relatively small.
  3. This approach works equally well when used with while loops.




+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes