开发者

How to keep track of objects for garbage collection

May I know what is the proper way to keep track of display objects created and hence allow me to remove it efficiently later, for garbage collection. For example:

for(i=0; i<100; i++){
var dobj = new myClass(); //a sprite
addChild(dobj);
}

From what i know, flash's garbage collection will only collect the objects without strong references and event listeners attached to it.

Since the var dobj is strongly referenced to the new object created, I will have to "nullify" it too, am I correct?

Should I create an array to kee开发者_JAVA技巧p track of all the objects created in the loop such as:

var objectList:Array = new Array();    

for(i=0; i<100; i++)
        {
            var dobj = new myClass(); //a sprite
            addChild(dobj);
            objectList.push(dobj);
        }

//remove all children
for each (var key in objectList)
{
     removeChild(key as myClass);
}

Does this allow GC to collect it on sweep?


var dobj is a local variable, so after your functions, that reference is gone. At that point, the only reference will be the fact that the item is on the display list (ie, that it's being displayed). So no extra work is needed for it to be garbage collected, just that you need to removeChild() it. Of course there could be other things elsewhere referencing it, such as event listeners, etc.

Your second code example should work, as long as you remember to no only remove them from the display list, but to also remove them from the array. Or you could use a Dictionary with weak references, then you wouldn't need to remove them from the Dictionary.


Yes this does allow GC to collect it if you have no other strong references to it, and it is what is usually done in flash.

The cast in the removeChild is unnecessary though.

Also, remember to set objectList to null or to a new Array() or set each element of it to null.


Most garbage collectors keep track of objects when they are created. The solution for languages like C++ (and a GC library) is allocating memory through a wrapper around new(). Something like:

var dobj = myNew myClass(); //a sprite

I dont know too much about Flex GC, but usually you should let it do its job. If it is based on strong references, then that will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜