how do I delete/gc an object in Actionscript 3?

evilpenguin picture evilpenguin · Apr 2, 2009 · Viewed 56.3k times · Source

I want to delete/force garbage collection on a class instance from inside itself. Obviously, this = null and delete this don't work. Is it any way I can do that, or am I barking up the wrong tree? I'm basically looking for a destructor of some sort..

I have a class instance that attempts to load an XML file, and if the file is not found, I want to destroy the instance, preferably from inside itself. The point is then to do some things in the parent class depending on whether the child instance is null or not.

I've thought of throwing an event to the parent and delete the child from there, but I'd prefer to do that only if there's no other way.

Answer

dragonfly picture dragonfly · Apr 2, 2009

You shouldn't attempt to remove object from itself - it is a bad practice, and in AS3 you can't do it for sure.

Object may be deleted (i.e. garbage collected) only if there are no references left to that object. Since references always get passed by value and object is generally not aware of which references to it exist, you can't delete object from itself. The only useful thing you can do is to create a method which will clean up all resources used by an instance. Such method will serve as a destructor, but you'll have to call it manually. Don't forget that event listeners will also prevent garbage collection unless you remove them.

There is also a difference between delete'ing a property and setting it to null. Effectively delete will remove a property from an instance of dynamic class. Whereas setting property value to null will not remove the property, but erase any reference that was stored there. Therefore both actions will destroy the reference that was stored in some property. Note, that you can't delete an object, only a property.

There are certain hacks that can be used to initiate garbage collection in flash players 9 and older ones. However recently System.gc() call got available, which does the same thing. Note, that you can't really rely on the fact that GC will actually be called. This is up to the flash player.

Returning to your question: throwing event and notifying parent that something went wrong is actually a good idea. You should stick to it. Moreover, it is better if parent will know of such event that way, and not when it will discover that some properties got magically nulled.

P.S.: Reading Grant Skinner articles on memory in flash player is actually a good idea.