Novice questions? What is the issue of releasing memory by local loaders within a function?
I wrote a function with a local variable ‘loader’ that loads an image, but the image is still in use. Why can ‘loader’ be set to null immediately?
There are multiple things going on in this code and in the background:
- Haxe utilizes the concept of garbage collection. By design, setting a variable to null in Haxe (and in other GC assisted languages) does not release the allocated memory immediately
- Even if you set the
loader
object to null, the underlying objects might still be using the allocated resources. As in your case, you’ve added the DisplayObject to the stage, said DisplayObject may have certain sub-objects initialized, and so on. Just by settingloader
to null does not remove the DisplayObject from the stage, it only de-referencesloader
(sets its pointer to null)
99.99% of the time you don’t have to manually free up the allocated memory and resources, that’s the Garbage Collector’s job. Advanced frameworks (like OpenFL) are also pretty good in releasing and freeing up resources wherever it’s needed. Just make sure you remove all of the references to the object (in your case remove the DisplayObject from the stage, all of its event listeners etc. and let the engine do its thing)
Adding to @igazine’s comments, it’s also a good idea to remove your event listeners once you don’t need them anymore to help make sure resources are properly released once their references are nullified.