AS3 GarbageCollection Utility

The below class serves as Garbage Collection utility for AS3. You can use it to prevent your applications from memory leakage.

package{
import flash.events.TimerEvent;
import flash.system.System;
import flash.utils.Timer;
public class GCUtil {
private var _timer:Timer;
public function GCUtil(interval_sec:uint = 60) {
_timer = new Timer(interval_sec*1000);
startGC(interval_sec);
}
public static function doGC():void {
System.gc();
}
public function startGC(interval_sec:uint):void {
if (interval_sec > 0) {
_timer.delay = interval_sec*1000;
if (!_timer.running) {
_timer.addEventListener(TimerEvent.TIMER, handleTimer);
_timer.start();
}
} else {
stopGC();
}
}
public function stopGC():void {
if (!_timer.running) {
_timer.removeEventListener(TimerEvent.TIMER, handleTimer);
_timer.stop();
_timer.delay = 0;
}
}
private function handleTimer(te:TimerEvent):void                       {
doGC();
}
}
}

  1. This seems a bit uneccessary – garbage collection is run automatically by the flash player. The only scenario where calling .gc() manually would make sense is right after your code have deleted lots of objects or references. And then you’d need to call system.gc() twice (once for mark, once for sweep)

  2. Agree to Torbjorn!

  3. Sure, me too agree!

  4. The other option would be to check total memory consumed by flash player and then accordingly call System.gc() when it crosses a set limit.

  5. Brilliant piece of work. I like and I think this is neccessary. Its just another method and its a good one

    • Mario
    • January 19th, 2009

    As far as I know, System.gc() just works in the debug but not in the release player. Furthermore the player handles the memory management.

    This code definitely does not prevent any leakage. To prevent memory problems you have to do stuff like cleaning your event listeners.

  1. January 15th, 2010

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: