Actionscript memory management, garbage collection

2020-03-26 12:32发布

问题:

This blog (and others) state that you should set object references to null inside your dispose() methods when cleaning up objects.

However, Actionscript 3 (with Flash Player 9) uses mark and sweep to clear out circular references for you. So I am wondering: is there really any reason to null out your object references?

回答1:

I never do - as long as you do the obvious:

  • Break all reference to the object (remove from arrays, set variables storing the object to null, remove from display list)
  • Remove all event listeners and so on

Then the memory that was used by the object is available for overwriting at any time.

var ar:Array = [];
var mc:MovieClip = new MovieClip();

mc.addEventListener(MouseEvent.CLICK, pants);

ar[ar.length] = mc;
addChild(mc);

if(mc.parent) mc.parent.removeChild(mc); // not garbage collected
mc.removeEventListener(MouseEvent.CLICK, pants); // still not garbage collected
ar.splice(0, 1); // finally garbage collected


回答2:

A fantastic summary of memory management is the Grant Skinner presentation:

http://gskinner.com/talks/resource-management/

In summary though, I never null the objects themselves, but null the objects referencing them (there is a subtle but important difference). All references need to the object need to be destroyed though, and also event listeners, etc.

When adding event listeners, get into the habit of setting the listener to be weak.

o.addEventListener(MouseEvent.CLICK, onClick, false, 0, true);

There is no disadvantage to this, and means that if you null all references to your object o but there is still listeners attached, they will remove themselves, and the object can still be marked for gc'ed. You should still handle your own removal of listeners regardless though.

"don't get lazy - clean up after yourself!"

Finally you can use the Janitor class to help monitor/clean up your resources:

http://gskinner.com/libraries/