Blog Hero Image

What is opened must be closed - AS3 Code Optimization

Mar 15, 2009
Brian Clark
Brian Clark

With computer processing powers the way they are today, small processor consumptions--like a minimal action that fires off every second--may not seem like a big deal to keep running. The issue that I have seen come in to play is when too many of these processes are never stopped or left to consuming client resources.

Using AS3, the example below demonstrates a simple way we can accomplish a reusable function that will act as a counter that works for 100 frames, does some action, then removes itself.

private function countingFunction():void {

var iCount:int = 0;
// initiate the counter
this.addEventListener(Event.ENTER_FRAME, myCounting_ENTER);
    function myCounting_ENTER ():void{
            if(iCount < 100){
                trace(�My Frame Count = �+iCount);

    // Removes enter frame when called
    function onEntFrRemove():void{
        removeEventListener(Event.ENTER_FRAME, myCounting_ENTER);

For some areas it may be easier to just use flash's built-in garbage collector, which was added with AS3, but this does not work so well for functions that need to continuously run check something or run till the end of some action.

For example if you where to use the same code above, to the code below, to change the way the listener was added to clean itself up with the flash garbage collector--it will most likely stop early due to the collector clearing the listener before its finished.

this.addEventListener(Event.ENTER_FRAME, myCounting_ENTER, false, 0, true);

* The 'true' at the end of the frame indicates that the garbage collector should take it on its next pass of the collector.

Remember to close things that are opened, use the garbage collector on functions that don't need to be running for a set amount of time, and use flash functions that process things for you when possible (no need to re-invent the wheel). Keeping these habits in your code should result in a significant improvement in your site or application's performance.

Latest insights