Flash AS3 Garbage Collection

New developers and/or Flash designers make the mistake of forgetting to clear an object when it is finished being used so that it is available for garbage collection. Many noobs simply don’t understand the importance and/or rules behind the Flash Player Garbage Collector. Some think that if you simply remove a child object from the stage, or simply made an object null, all is done and memory is automatically freed up. This is a misnomer and if you continually add large objects at runtime, especially with bitmaps and video, you quickly see a performance hit to the processor. This slowness is evident more quickly on slower computers, like the one I have at work, than on newer/faster computers. Sometimes it is a good thing to test on slower computers to help indicate if your application is overly obtuse due to poor garbage collection.

I have made many of common errors of non-garbage collection myself and have found it imperative to clear any (even weak) reference to an object. I found that it is easiest to do this early on in development while you are adding the reference to think of the way it will be removed. For example, when you add and event listener, know when that event listener is finished and remove that event listener:

var image:Loader = new Loader();
var urlReq:URLRequest = new URLRequest("image.jpg");
image.load(urlReq);
image.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
function completeHandler(event:Event){
    //once image is loaded you can stop listening for it to load
    event.target.removeEventListener(Event.COMPLETE, completeHandler);
}

I have found that it is best to set up a class for an image loader as it is something that gets used over and over. One thing for certain to use within your ImageLoader class is an unload listener that will remove all soft references to the object so that it will be available for garbage collection.

function unLoadHandler(event:Event) {
    // remove any listener you have created if you want it to be disposed of durring GC.
    event.target.removeEventListener(Event.UNLOAD, completeHandler);
    // you should have set up a error handler listener. Be sure to remove it as well
    event.target.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
}

This way when you say image.unload(), your Loader Object will remove all listeners to that object so that it can be disposed of automatically when the Garbage Collector hits. Personally I think this should be automatic by default and remove any and all references to the object, but it is not and it is up to the programmer to set it up that way.

Once you make a conscious effort to be aware of the way the garbage collector works, you will more readily be able to remove all references to the object. If you add the code to remove the listener while it is on your mind to add the listener, you can keep your application cleaner and leaner for a better end-user experience.