Actionscript memory management, garbage collection

我与影子孤独终老i 提交于 2019-12-30 11:18:10

问题


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/



来源:https://stackoverflow.com/questions/5877674/actionscript-memory-management-garbage-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!