Search code examples
actionscript-3flashmemoryair

Detail lifespan of all ActionScript3 object


I use ActionScript3 to develop web and mobile game. Memory is my biggest enemy, I always don't know detail lifespan of some objects. For instance: Bitmap I know there is a "dispose" function of bitmapData. So always, I dispose a bitmap object by using "bitmap.bitmapData.dispose". However, I wonder if the reference of a bitmap object becomes 0, will GC free the memory used by this object even if I don't call dispose function.

I have too many questions like above (Sound, Texture, BaseTexture...). Does anyone has some ideas about this topic?


Solution

  • The object's lifespan is determined by one single thing - if it's no longer referenced from anywhere, it's considered dead (orphaned) and is a subject to be removed from memory. So yes, a BitmapData object will be removed from memory even without explicit dispose() call, if you drop all references to it.

    About Sound or Texture objects - these are best being reused, for example, you can call mySound.play() multiple times, this will generate a separate SoundChannel object which lifetime is about the duration of the sound, if it's unreferenced. Likewise you can use same Texture object to have multiple instances of something being textured with it.

    There is a special rule concerning those classes that extend EventDispatcher, as they can listen to events, and if you will not use weak reference to that object, an event listener is attached directly to the instance, thus making an extra reference link which will effectively prohibit GC from recycling memory occupied by that object. So you should always have total control over all strong-reference listeners, at least for this purpose.

    Hope this helps.