Garbage Collector

Wednesday, June 3, 2009

Throughout the past few applications that I've made at work, I've found constantly run into one problem that I spend a lot of time tweaking. Managing memory. Actionscript 3 does not automate this process very well. I've found a few helpful techniques to run the Garbage Collector at will, although I still feel that it is a wild and uncontrollable wind, I'm at least hopeful to control it.

GSSkinner explains the concepts really well.
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html

One of my most used methods of manual garbage collection is to remove all children in a main section MovieClip, just before I remove it from stage.
for example


//remove all of the children
while(parent.numChildren > 0){
parent.removeChildAt(0);
}

//remove the parent
removeChild(parent);

//run the garbage colletor
import flash.system.System;
System.gc();

Also you can monitor the swf's total memory usage via
System.totalMemory;
I usually set up something like this


private var peak:Number = 0;
private function mem_test():void{
if (System.totalMemory > peak)
peak = System.totalMemory;

mem_txt.text = "current memory: " + (System.totalMemory/1024).toString() + "\r" + "peak memory: " + (peak/1024).toString();
}

setInterval(mem_test,1000);

2 comments:

Daryl said...

Is there a performance penalty for constantly removing the first item in your parent collection?

parent.removeChildAt(0);

Kyle said...

That's a good question. I'd say that there's more of a performance cost if you leave it there if not using it on stage.

Post a Comment