views:

246

answers:

1

Once again a question about the garbage collector in actionscript-3:

If I have a master container:

var masterContainer:Sprite = new Sprite();

And then I add a child to this container:

var childImage:Sprite = new Sprite();
masterContainer.addChild(childImage);
addChild(masterContainer);

And, I then decided to let the garbage collector collect the master container and all it's contents, will this be enough?

removeChild(masterContainer);
masterContainer = null;

Or do I have to store all child images' references somewhere just to be able to remove their childs from the master container later?

Also, would it be possible to let the garbage collector log a message when it deletes something and what exactly it is deleting? Somekind of event maybe?

+3  A: 

The first part of your question:

Technically speaking it is enough. Although this depends on the side effects. If you have non-weak listeners nothing will be GCed.

Second part:

You can have a Dictionary with the object you want to monitor as a weak key. Then run a timer and see when this is deleted.

Joa Ebert
"If you have non-weak listeners nothing will be GCed". I disagree. You can have strong listeners attached, as long as the object you're listenening is eligible for GC. I.e. this doesn't apply to the stage, running timers or objects that are referenced by objects that are not collectable (because they're in active use).
Juan Pablo Califano
Non-weak listeners will add to the reference count of the object and will prevent it from being eligible for GC. It will never be marked and hence when the GC runs it won't get cleaned. Now if you remove the listener you're fine - but while that listener is attached, the object has a non-zero reference count so it's not going anywhere.
Branden Hall
Nice to see you on Stackoverflow Joa!
Tyler Egeto
Branden, I'm afraid you're wrong. Reference count is just a part of GC. You have to take into account "root" GC objects, that are used to traverse the active objects tree. People often forget about that and "detect leaks" checking System.totalMemory, so they think they have a leak when that's not necessarily the case. Check this sample with a profiler if it's available to you (and you feel like doing it anyway ;) http://pastebin.be/20568
Juan Pablo Califano
You'll see the number of current instances of MySprite will grow. But if you force a GC cycle, all instances will be freed after you remove MySprite. Note that I'm not removing the hard-referenced listener.
Juan Pablo Califano