Weak listeners are bad
Tuesday, September 28th, 2010The Flash Player has a problem with cleaning up memory for AS3. Storing a reference to an object blocks the Garbage Collector from disposing the object and the object will be kept in memory. That’s why a lot of developers set ‘useWeakReference’ to true when adding an event listener.
1 | addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void |
“A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not.”
I think using weak listeners is bad practice - don’t do it!
When setting a listener as weak the responsibility of the operation of your application is transfered to the Garbage Collector, which isn’t reliable at all. If and when the Garbage Collector is running is completely random[1]. You never know if or when your listeners are removed, which makes your application unreliable and unstable. Weak listeners are used by lazy developers who don’t want to take responsibility for cleaning up their own code.
Removing event listeners should always be the responsibility of the developer (or application) and not the Garbage Collector. So if you add an event listener be sure you also remove it when the object should be disposed.
There is only one exception for using weak listeners: adding listeners to the stage. Since the stage will never be disposed and the only reference to an object is the reference to the stage, there is no need for this object to exist. But still you have to remove this (weak) listener when this object should be disposed!
Temple
If you do not want to remove all listers by hand, you could use Temple Library. This toolkit has a destruction model which automatically removes all (strong) event listeners when an object is destructed and makes the object available for garbage collection. But even if the Garbage Collector isn’t running your destructed objects won’t unnecessary listen for events.
The Temple is open-source and available on GoogleCode: http://code.google.com/p/templelibrary/
[1] I know there are some tricks to force a garbage collection, but those are all unsupported. So a Flash Player update could break those tricks.
If you have a function reference in Flash there is not a lot of information you can get from it. Converting the function to a string will only give you: 
A few weeks ago we launched the new website for We Fashion.
I am a huge fan of
When I saw the 








