垃圾回收最佳实践 [英] garbage collection best practices

查看:212
本文介绍了垃圾回收最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您要从显示列表中删除MovieClip,并且该MovieClip又具有拥有自己的事件侦听器的子级动画片段,是否需要从子级动画片段中删除所有侦听器?



或者只是直接从显示列表中删除的父级MovieClip?

解决方案

附加到父级或子级MovieClip的侦听器都有弱引用指向它。



添加侦听器时,可以使用最后一个参数来设置如果侦听器将使用弱引用。这正是你所要问的问题。

  //这个监听器将使用一个弱引用,注意lasttrue
something.addEventListener(event,myFunction,false,0,true);
//这被称为弱引用侦听器。
//具有默认参数的漫游侦听器是一个强大的拒识侦听器。

EventDispatcher Reference

所以一个对象会被垃圾收集if所有对这样的对象的引用都被删除。添加了默认参数的监听器会计入这些引用(因为最后一个参数默认值是 false )。因此,如果MovieClip具有附加到它或其子任何强引用侦听器的MovieClip,则通过将其从显示列表中删除,该剪辑将不会被垃圾收集,直到侦听器引用也被删除(通过使用 removeEventListener 方法)。

如果您在剪辑或其任何子项中使用弱引用,则通过从显示列表中删除它,它最终会垃圾收集。请记住,这可能会在一段时间后发生,所以像 ENTER_FRAME 这样的事件可能仍会被触发并被调用,直到对象最终被收集。


If you're removing a MovieClip from the display list, and that MovieClip in turn has child MovieClips which have their own event listeners, is it necessary to remove ALL listeners from the child MovieClips?

or just the parent MovieClip that is being directly removed from the display list?

解决方案

It depends if the listeners attached, to either the parent or children MovieClips, have weak references pointing to it or not.

When you add a listener, you can use the last parameter to set if the listener will use a weak reference. This is exactly what you need to know for the question you ask.

//This listener will use a weak reference, notice the last "true"
something.addEventListener("event", myFunction, false, 0, true);
//This is called a weak reference listener.
//The ussual listener, with default parameters, is a strong refence listener.

EventDispatcher Reference

So an object will be garbage collected if all the references to such object are deleted. Listeners added with the default parameters count toward those references (since the last parameter default value is false). So having a MovieClip with a strong reference listeners attached to it or any of its children, by removing it from the display list the clip will NOT be garbage collected until the listener references are also deleted (by using the removeEventListener method).

If you use weak references in a clip or any of its children, by removing it from the display list it will eventually be garbage collected. Have in mind that this may occur after some time, so events like ENTER_FRAME may be still be triggered and called until the object is finally collected.

这篇关于垃圾回收最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆