开发者

Most efficent method for removing children from a DisplayObject in as3? (Memory)

开发者 https://www.devze.com 2023-03-27 19:41 出处:网络
What wo开发者_开发技巧uld be the most efficent way to remove the children from a sprite/movieclip in respect to memory and garbage collection?

What wo开发者_开发技巧uld be the most efficent way to remove the children from a sprite/movieclip in respect to memory and garbage collection?

I have seen atleast three ways.

Simple re-assigment

sprite = new Sprite();

null and then new

sprite = null
sprite = new Sprite();

or the while removal (which I am fond of)

while(sprite.numChildren > 0){   
    sprite.removeChildAt(0); 
}

I am just learning about clean and good memory management, any VALID input would be appreciated, thank you.


removeChild or removeChildAt does not actually remove an Sprite or any other DisplayObject from memory, it only removes it from the displaylist. That means if you create 1000 sprites and add them to the stage (displaylist), and then use removeChild on all 1000 sprites they could still exist in memory forever.

To remove it from memory, it should be set to null at all referencing objects.

If you really want to remove it, just null it and check these things:

  • Remove it from the displaylist using removeChild or removeChildAt
  • Remove all eventListeners that are attached to the clip.
  • If you used a reference in an Array, Vector, Dictionary or any other object, remove it from the object, set it to null or splice it using Array.splice()
  • Set the object = null

You could use a solution like an EventManagedSprite which uses an EventRemover to make it a bit easier to completely remove objects. This also could be helpful in bigger projects.

If you want to re-use the sprite/object, but recycle you want to recycle the objects, you should use object pooling. More about object pooling with AS3:


removeChild / removeChildAt removes the DisplayObject from its parent; it still remains in memory and you can add it later if you want (as long as you have a reference to it).

In my experience, removeChild + null assignment is the best way to remove the DisplayObject and save on memory.

Cheers,

0

精彩评论

暂无评论...
验证码 换一张
取 消