After having some trouble with object deletion, I ran a simple test:
- Created a simple class with a weak reference listener for Event.ENTER_FRAME.
- Added a
trace("I Exist!")call to the listened function. - Instantiated a single instance with one reference in the Document Class.
This worked as expected – the SWF file did nothing but print “I Exist!” every frame to the console. (In debug mode, of course.)
What I did next did not work as I expected:
I set the only reference of the object to be set to null on a mouse event, but the messages from the event listener of of said object still appeared in the console after the mouse event was fired and the reference set to null – meaning the object still existed!
Calling System.gc() in the document class IMMEDIATELY stopped the event listener from printing further messages and seemingly deleted the item.
From what I understand, calling System.gc() is discouraged, but as it seems from this simple test the garbage collector is a big FAIL.
Am I doing something wrong here in trying to dispose of the object, or should I simply call System.gc() every time I want to get rid of an object..?
Edit: Calling System.gc() with a non-weak listener also results in the object seemingly being removed from memory (?)
Garbage collection is almost always deferred in modern VMs (Java, Flash Player, .NET, etc.). You can read http://www.adobe.com/devnet/flashplayer/articles/garbage_collection.html for more information.
In particular: