Rethinking addEventListener and Memory Management

When I open the Flex builder help and look at the documentation for EventDispatcher's addEventListener, I see:

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Objects with registered event listeners are not automatically removed from memory because the garbage collector does not remove objects that still have references.

This is what the documentation said when I was first learning Flex, and it's not surprising that I had formed the conclusion, somewhere along the line, that the object that you added the listener to is the one that can't get garbage collected. And until recently, I never questioned this perception.

However, I had a discussion last week with a coworker where he asserted that the opposite was true–that using addEventListener will keep the object that is listening in memory. One of the great things about having disagreements is that it forces me to go back and revisit my conclusions so that I can defend them. And I found something interesting. Without any fanfare, the online documentation for addEventListener has changed to this:

If you no longer need an event listener, remove it by calling removeEventListener(), or memory problems could result. Event listeners are not automatically removed from memory because the garbage collector does not remove the listener as long as the dispatching object exists (unless the useWeakReference parameter is set to true).

I started to think about this change in the docs, and I realized that addEventListener is, of course, a method of EventDispatcher. You can add an event listener within a Class that does not implement IEventDispatcher.

This means that the Class with the function that gets called when the Event is generated does not have to have anything to do with EventDispatcher. And the whole point of using Events for communication is that it makes it possible for a Class to process information from places it knows nothing about.

On the other hand, for an EventDispatcher to call the function, it has to have a reference to it. In other words, addEventListener simply adds the function as a callback to the IEventDispatcher object, to be called at the time of dispatch. Duh.

For more on how adding event listeners affects memory management, check out Alex Harui's Garbage Collection and Memory Leaks.

About this Entry

This page contains a single entry by Amy Blankenship published on August 11, 2010 6:32 PM.

New Flash Player adds H.264 GPU support on OSX was the previous entry in this blog.

Experimenting with Different Teaching Methodologies is the next entry in this blog.

Find content using the provided navigation or look in the archives to find all content.

Authors

Archives

This content archive is licensed under a Creative Commons License.