davidkomer
davidkomer

Reputation: 3078

Garbage collecting anonymous functions in Actionscript

Let's say there's a class which loads a bunch of images and dispatches an Event.COMPLETE when finished. We'll call it AssetLoader

Then we have our main document class which does something like this:

    var myAssetLoader:AssetLoader = new AssetLoader();
    myAssetLoader.addEventListener(Event.COMPLETE, function():void {
     doStuffWithImages();
    });

    myAssetLoader.loadURLS("http://example.com/image1.png", "http://example.com/image2.png");

    //Some time later, after doStuffWithImages()
    myAssetLoader = null

Will myAssetLoader be completely garbage collected? i.e. without any removeEventListener?

Upvotes: 0

Views: 98

Answers (2)

Sunil D.
Sunil D.

Reputation: 18193

In this case, yes, your AssetLoader would be garbage collected. Whether the event handler is an anonymous function or not.

The key is paying attention to which object maintains the reference to the other object when adding an event listener: When you say a.addEventListener("event", b.eventHandlerFunction), the "a" object maintains a reference to the "b" object (when the event happens "a" needs to execute the event handler in "b").

So if we discard "a", and keep "b" in memory, "a" can be garbage collected because no object has a reference to it. In your case "b" is the main document class, which the anonymous function belongs to... and "a" is the AssetManager.

That being said the advice given in the other answer are still good practices to follow, even if you know your objects will get g/c'd.

Upvotes: 1

Tim
Tim

Reputation: 2161

You should removeEventListener before setting the references to null.

  • Delete all references to objects to make sure that garbage collection is triggered.
  • Setting a reference to a display object to null does not ensure that the object is frozen. The object continues consume CPU cycles until it is garbage collected. Make sure that you properly deactivate your object before setting its reference to null.
  • If an object was used as an event listener, another object can reference it. If so, remove event listeners using the removeEventListener()method before setting the references to null.

Upvotes: 1

Related Questions