Wednesday, April 7, 2010

Flex, Memory Management, and Event Listeners

ActionScript (the language used in the Flex framework) is a language in which GC is handled for you.  It's a great convenience, and makes coding quite a bit easier.  As with any automatic GC language, you have to keep track of your references and make sure they are cleaned up, but it's not terribly hard to do.

And yet, there's one subtle memory leak which can really bite you in the butt: event listeners.

When you add an Event Listener to a component, its default state (unless changed) will be as a "strong" reference.  This means the listener will not be cleaned up when the Garbage Collector runs.  As a result, any references the listener might have might not be cleaned up; this can wreak havoc on your code when components are rapidly added/removed.  The number of objects persisting in memory which can't be harvested may in turn cause further spikes as the Flash Player needs more room to work with.

Adobe's Flex 3 documentation describes Event Listeners and weak references as thus:

useWeakReference:Boolean (default = false) — Determines whether the reference to the listener is strong or weak. A strong reference (the default) prevents your listener from being garbage-collected. A weak reference does not

There are two ways of mitigating this.  If you chose to create Event Listeners as thus:

button.addEventListener(MouseEvent.CLICK, doSomething);

You should create a deconstructor which removes the listeners prior to tearing down the component:

button.removeEventListener(MouseEvent.CLICK, doSomething);

The other option is to create the listener and force it to use weak references:

button.addEventListener(MouseEvent.CLICK, doSomething, false, 0, true);

Thus, when the component is GC'd, the listener will be also.

No comments:

Post a Comment