views:

76

answers:

1

Can someone post an example of as3 code (specifically event listener included) that would be a simple example of something that could leak memory... also hopefully could you post a solution to the problem shown?

The question is: What is a simple example of leaking memory in an AS3 event listener and how can you solve it?

+1  A: 
public class MySprite extends Sprite {

    public function MySprite() {
        if(stage) {
            init();
        } else {
            addEventListener(Event.ADDED_TO_STAGE,init);
        }
    } 

    private function init(e:Event = null):void {
        stage.addEventListener(Event.RESIZE,handleStageResize);
    }

    private function handleStageResize(e:Event):void {
        //  do some processing here.
    }

}

Somewhere else:

var mySprite:MySprite = new MySprite();
someHolder.addChild(mySprite);

Now, if at some later point you remove mySprite, it'll still hang around in memory, because it has added itself (or a reference to itself) to the stage in the init() method.

In this scenario, the best way to avoid this could be removing the listener added to the stage when mySprite is removed from the display list.

    private function init(e:Event = null):void {
        addEventListener(Event.REMOVED_FROM_STAGE,cleanUp);
        stage.addEventListener(Event.RESIZE,handleStageResize);

    }

    private function cleanUp(e:Event):void {
       stage.removeEventListener(Event.RESIZE,handleStageResize); 
    }

I'm sure other people will tell you to use weak references when adding the listener to the stage, but you should remove your listeners anyway. If you don't, when you remove mySprite from the display list and have no other refs to it, will be eligible for GC and will eventually be wiped away from memory. But until that happens, the code in handleStageResize() will continue to execute.

Juan Pablo Califano