Flex Tip 6: Garbage Collection in Flex

March 17, 2008 – 7:34 am

One of the hot-spots in Flash platform is related to memory, how is it distributed inside the runtime environment, memory leaks and of course garbage collection. The way that memory allocation takes place inside Flash is by instantiation, every time a new Object is created, a memory block is created for it. The problem comes when that Object is freed because its block will not always be re-used by the next allocation. The simple “freed” action wont mark it unused, only Garbage Collection will mark it unused, GC that is ONLY triggered by allocations meaning that if there are no instantiations in the application, its memory usage will not change.

Now how GC works in its deeps depends a lot on how you build your application, if you remove event listeners from deleted objects, if you re-use your already created object instances and so on. Garbage Collection IS NOT PREDICTABLE, it cant say that your application is bullet proof, that is not leaking memory.

One trick that you can use to force a garbage collection in your Flex application is by using this statement:

try
{
      var lc1:LocalConnection = new LocalConnection();
      var lc2:LocalConnection = new LocalConnection();

      lc1.connect( "gcConnection" );
      lc2.connect( "gcConnection" );
}
catch (e:Error) {}

The simple instantiation of LocalConnection will trigger a full garbage collection, a nice solution you can use in your application.
Even using this doesn’t assures use that you don’t have memory leaks inside the app, it really depends on how you write your code, if you write it with GC in mind.

As a reassurance in this matter, next releases will have memory diagnostic tools helping you find any memory leaks your app might have. Until then use the tip with LocalConnection and also there can be made automated test sequences in ActionScript that tests the application without human intervention (like faking mouse or keyboard events).

Post a Comment