« Deep Object Copy
» Framework spotlight

ActionScript, Events, Flex 2

Garbage Collector and events

Virgil Cristea | 26.10.07 | Comment?

A feature of Flex (and any decent programming language) is the garbage collector. What it does? Once it detects that an object in memory is no longer needed it will clean up the memory. Simple no?

Well is not that simple: you may have finished your work with that object but there are references to it. In this case the garbage collector cannot collect that object.

In Flex one of the main reasons this can happen is because of event handlers that are forgotten to the object.

Let’s take a look at the following code:

var myTestComponent:Canvas = null;
myTestComponent = new Canvas();
myTestComponent.addEventListener(MouseEvent.CLICK,testHandler); //testHandler is a function
myTestComponent = null;

This code will destroy the component but the memory associated to it cannot be collected as a reference exists (the event callback function: testHandler). In order to be able to collect the object before you make the object null you need to do the following:

myTestComponent.removeEventListener (MouseEvent.CLICK,testHandler);

That will remove the reference and then it can be collected when you make the object null.

Another way to get the same functionality is to use weak listener references. This will in fact inform the garbage collector to skip the weak link types:

myTestComponent.addEventListener(MouseEvent.CLICK,testHandler, false, 0 , true);

The last parameter makes this listener a weak reference. This means that the function is eligible for garbage collection. This of course is not the same as it will be garbage collected. If the memory used by your application is not high enough then it will not be collected.

In general it is not a good practice to rely on the usWeakReference. You should add and remove the event listeners in your programs before destroying the objects where they are used.

Share and Enjoy:
  • Technorati
  • StumbleUpon
  • del.icio.us
  • NewsVine
  • Reddit
  • Digg
  • Furl
  • co.mments
  • blogmarks
  • Slashdot
  • description
  • Taggly
  • YahooMyWeb
  • connotea
  • Webride




Tags: , , ,

This post was written by Virgil Cristea

Views: 1156

related

have your say

Add your comment below, or trackback from your own site. Subscribe to these comments.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="">

:

:


« Deep Object Copy
» Framework spotlight