Actionscript 3: Do self event listeners prevent an object from being garbage collected?

前端 未结 2 346
轮回少年
轮回少年 2021-01-24 19:52

I know that event listeners and references to an object will prevent the garbage collector from dealing with objects. My question is, will an event listener placed on an object

2条回答
  •  温柔的废话
    2021-01-24 20:08

    No, but.

    The AVM2 garbage collector is supposed to find unreachable objects. But because garbage collection is non-deterministic, it's very hard to rely on or even test this behaviour -- it could be that the garbage collector is working perfectly, but not bothering to run the mark-and-sweep since you have enough RAM free.

    It's a good idea to remove event listeners when you're done with the object, even if they're from the object itself (i.e. circular references). Why is this a good idea? Because you never know when the garbage collector is going to run. If you want deterministic behaviour, always remove listeners in a deterministic fashion, especially for time-sensitive events like TIMER and ENTER_FRAME, otherwise you're creating a race condition between your listeners running and the garbage collector running. The garbage collector only runs periodically.

    In general, if you want to attach event listeners without creating an additional reference to the object, pass true to the useWeakReference parameter of addEventListener(). If you want to stop receiving the events right away, though, you'll still need to manually detach your event listeners as soon as you're done with the object.

提交回复
热议问题