User Guide
120 Chapter 3: Using Best Practices
Optimizing ActionScript in Flash Player
There are several ways that you can optimize your code for better SWF file performance, but
remember that optimizing your code for Flash Player might reduce readability and consistency for
code maintenance. Only practice optimize your code when necessary. Follow these guidelines to
optimize your ActionScript for Flash Player:
• Avoid calling a function multiple times from a loop. It is better to include the contents of a
small function inside the loop.
• Use native functions, which are faster than user-defined functions.
• Use short names for functions and variables.
• Delete your variables after you no longer use them, or set variables to null if you do not delete
them.
Note: Setting variables to null instead of deleting them can still reduce performance.
• Avoid using the eval() function or array access operator when possible. Often, setting the
local reference once is preferable and more efficient.
• Define a my_array.length before a loop, rather than using my_array.length as a loop
condition.
• Focus on optimizing loops, setInterval, onEnterFrame, and onMouseMove, which is where
Flash Player spends a lot of time processing.
Stopping code repetition
The
onEnterFrame event handler is useful because it can be used to repeat code at the frame rate
of a SWF file. However, limit the amount of repetition that you use in a Flash file as much as
possible so that you do not impact performance. For example, if you have a piece of code that
repeats whenever the playhead enters a frame, it is processor-intensive. This can cause
performance problems on computers that play the SWF file. This section discusses how to do
this, and also how to remove movie clips and stop repeating code. If you use the
onEnterFrame
event handler for any kind of animation or repetition in your SWF files, end the
onEnterFrame
handler when you finish using it. In the following ActionScript, you stop repetition by deleting
the
onEnterFrame event handler:
circle_mc.onEnterFrame = function() {
circle_mc._alpha -= 5;
if (circle_mc._alpha<=0) {
circle_mc.unloadMovie();
delete this.onEnterFrame;
trace("deleted onEnterFrame");
}
};
Similarly, limit the use of setInterval, and remember to clear the interval when you finish using
it to reduce processor requirements for the SWF file.