Loops and Repeated Operations
Most of your performance problems are going to be the result of a repeated operation that is not optimized. A nonoptimized piece of code that executes one time is not likely to have an impact on an application; however a nonoptimized piece of code that executes 1,000 times in a loop is going to kill the performance. For that reason, any code that is executed repeatedly, such as an onEnterFrame( ) handler or a for loop is a potential bottleneck.
Macromedia improved the performance of the Flash Remoting classes in the first updater, available at http://www.macromedia.com. One technique that was originally used throughout the Flash Remoting classes involves initializing a for loop in a nonoptimized way. In standard ECMA scripting, the middle section of the for loop (the condition in the for(variable; condition; update) construct) is evaluated each time the loop executes. For that reason, a static value should be used whenever possible.
Bad:
for (var i = 0; i < this.getLength( ); i++) {
// Do something
}Good:
var tempLength = this.getLength( );
for (var i = 0; i < tempLength; i++) {
// Do something
}However, counting down is even faster:
var tempLength = this.getLength( )-1;
for (var i = tempLength; i >= 0; i--) {
// Do something
}Optimizing a loop’s condition expression is only the first step. Code within the loop should be optimized whenever possible, for this is where your application performance is going to suffer the worst. This is especially true ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access