Yesterday I ran into a memory leak. After digging all the way down, I found it was caused by the bitmap captured for the reflection in an external .swf that had been loaded not being cleared. My guess is that although loader.unloadAndStop() closes the stream, it doesn’t release the BitmapData created inside the loaded program.

Keep this in mind: aside from purely media-playback objects, if the external program you load has listeners, callbacks, or has created BitmapData, then that external program needs to clean up after itself before it’s unloaded. Otherwise, no matter how much you gc, it’ll still be eating memory.

Solution:

In this kind of situation, I usually have the loaded flash program implement a dispose method, and the loader that loads it calls dispose(); inside a try before unloadAndStop();. The external program cleans up after itself inside the provided dispose method. The cleanup steps differ from case to case — you have to take out your own self in a targeted way, based on everything you did while you were alive. Broadly speaking, this includes: cutting off your related callbacks and listeners, and freeing memory (closing sounds, clearing video, closing network connections, clearing bitmap data).

Like this, in the main file: private function closeExFlash() : void { try { (exFlashLoader.content as IDispose).dispose(); }catch(e : *) { } try { exFlashLoader.unloadAndStop(); }catch(e : *) { } this.visible = false; }

There’s another approach: the loaded Flash maintains itself. This only works when the document class is placed directly onto the stage — I don’t often do this (in many cases I use the swf as a runtime sharelib, and I load it just to use some of its classes) — The loaded Flash listens for the remove\_from\_stage event itself, and when that event fires, it frees its own memory: cutting off its related callbacks and listeners as described above, and freeing memory (closing sounds, clearing video, closing network connections, clearing bitmap data). At the same time, make sure the main program holds no references to it.