I will be dealing with this in the next installment of my resource management series of articles, but I thought it was important enough to warrant a quick post in the interim.

I've been blogging about how important resource management is going to be in ActionScript 3, and also mentioned that we have some new tools to deal with it. One of these new tools is the ability to have weakly referenced event listeners. A weak reference is one that is not counted by the Garbage Collector (ie. it is not counted in reference counting, and it is not followed for mark sweeping). This means that if the only references remaining to an object are weak, it will be available for collection on the next GC sweep.

References associated with event listeners are often forgotten by developers, which normally results in the listener never being removed from memory. This is why weakly referenced event listeners are so handy in AS3 - if you forget to remove the listener, you will not impede the Garbage Collector's ability to collect the object.

It's easy to use weakly referenced listeners in AS3. Just set the fifth parameter of an addEventListener call to true:

// params: eventName, listener, capturePhase, priority, useWeakReference
someObj.addEventListener("eventName",myFunct,false,0,true);
I would very strongly recommend getting in the habit of ALWAYS setting your listeners to be weakly referenced. I can't think of any good reasons to set it to false, so I'm kind of disappointed that it wasn't set to use weak references by default, although I understand the rationale. The one place weakly referenced listeners fall apart is in the case of anonymous functions:
addEventListener("eventName",function(evt) { ...code... },false,0,true);
In the above example, the only reference to the anonymous function I defined in-line is the weak reference from the event dispatcher. This means the next time the GC sweeps, my function will be removed, and obviously will no longer be called. This can be very confusing to debug, because the indeterminate GC will make the results seemingly random.

Using anonymous functions in this way is bad practice though (both architecturally, and because it leaves you with no way to remove the listener), so I'd still argue for weak references by default. This is a little selfish though, because I know that we are going to have problems in the future with third party content creating strongly referenced stage listeners (and thus never being garbage collected), whereas my team will never encounter the anonymous function issue (unless it's in debugging third party content).

So please (PLEASE!), get in the habit of always setting your event listeners to be weakly referenced. It's a little bit of extra typing, but it'll save everyone (you, your users, anyone that needs to integrate with / consume your content) a lot of headaches.

Kudos to Adobe for providing this functionality!