I noticed something dangerous while working with AS3 – some objects (namely DisplayObjects / MovieClips) tend to remain in the memory and even perform actions after all references to them have been removed.
I work with Flash CS 5.5 and Flash Builder 4.6.
After getting rid of all references (including removeChild(…) from the Document Class) some objects just seem to stay alive.
This question might come off as a bit broad – but what I am trying to understand is what can I do to MAKE SURE that an object is picked up by the Garbage Collector?
More so, how can I get some sort of feedback from the GC that signifies that a certain object has been destroyed? (For example, a console message)
Thanks in advance.
Removing the object from the stage, removing event listeners and setting all references to
nullshould be enough – GC will pick it up when it is next executed.It is tedious to keep track of all references, however (and remember this includes event listeners, unless you’ve set
useWeakReferenceto true), if you don’t have a standard way of doing it… It is advisable to have a “destructor” function in every class, which takes care of cleaning up all variables and event listeners when an object is no longer needed.You can combine these with events, too – I’ve come to think that it is good practice to execute your
init()function onEvent.ADDED_TO_STAGEand thedestroy()function on Event.REMOVED_FROM_STAGE. That way you have a clearly defined life cycle for stage objects, and if you make sure yourdestroy()method stops all animations and sounds, removes all children and event listeners and sets all member variable fields tonull, you can be quite sure there’s no longer any activity going on that could produce unwanted side effects.By the way – if you actually notice any activity by an object you have removed, some references must certainly still be intact – how else would you be able to tell?
Still, there’s no way to know when exactly GC will pick up a discarded object – this is managed by the VM, and you’re not going to get a message when it is done. And it shouldn’t be your responsibility to think about when to free memory – after all, that’s exactly what garbage collectors were invented for!
If you make it a habit to clean up after yourself, your programs will unavoidably become more stable, consume less memory and ultimately perform better. That’s all that should matter.