当删除对象时,对象内部的setInterval是否可以防止垃圾回收? [英] Does setInterval inside an object prevent garbage collection, when the object is deleted?

查看:67
本文介绍了当删除对象时,对象内部的setInterval是否可以防止垃圾回收?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个小的Websocket项目(使用Socket.io),在其中使用了这样的类:

function myClass() {
    // start server sync
    window.setInterval(this.update.bind(this), 14);

    // listen for socket.io events
    io.on('my-event', doStuff);
}

在一个数组中存储了该类的多个实例. 一段时间后,实例将像这样被删除:

myArr.splice(index, 1);

数组是唯一的位置,我将实例存储在其中,因此我认为,将实例从数组中删除后,实例将被垃圾收集器删除.

相反,我注意到,他们仍然响应我的websocket事件.我想知道间隔是否阻止对象被删除,因为它绑定到窗口对象. 我需要在删除类实例之前清除间隔吗?

还是事件监听器阻止对象被删除?

解决方案

...实例被这样删除:

myArr.splice(index, 1);

...相反,我注意到,他们仍然响应我的websocket事件.我想知道间隔是否阻止对象被删除,因为它绑定到窗口对象.我需要在删除类实例之前清除间隔吗?

是的,您需要进行更多清理.您需要:

  • 清除间隔,以清理与其相关的资源,并使其释放对this.update.bind(this)创建的函数的引用(该引用又对该对象的引用,并将其保留在内存中).

  • 删除所有事件侦听器(例如Web套接字事件),这将删除它们对事件处理程序函数的引用,该事件处理函数可能引用了将其保留在内存中的对象.

  • 确保还释放了对该对象的任何直接或间接引用(例如在任何其他绑定函数中).

I am working on a little Websocket project (using Socket.io), where I use a class like that:

function myClass() {
    // start server sync
    window.setInterval(this.update.bind(this), 14);

    // listen for socket.io events
    io.on('my-event', doStuff);
}

There are multiple instances of that class stored in an array. After some time, the instances get deleted like that:

myArr.splice(index, 1);

The array is the only location, I store the instances in, so I thought, they would get deleted by the garbage collector after removing them from the array.

Instead I noticed, that they still respond to my websocket events. I am wondering if the interval prevents the object from getting deleted, because it is bound to the window object. Do I need to clear the interval before deleting the class instance?

Or does the event listener prevent the object from being deleted?

解决方案

...the instances get deleted like that:

myArr.splice(index, 1);

...Instead I noticed, that they still respond to my websocket events. I am wondering if the interval prevents the object from getting deleted, because it is bound to the window object. Do I need to clear the interval before deleting the class instance?

Yes, you need to do more cleanup. You need to:

  • Clear the interval, to clean up resources associated with it and make it release its reference to the function created by this.update.bind(this) (which in turn has a reference to the object, keeping it in memory).

  • Remove any event listeners (e.g., web socket events), which will remove their references to the event handler functions, which probably have references to the object that keep it in memory.

  • Ensure that any other references to the object, direct or indirect (such as in any other bound functions) are also released.

这篇关于当删除对象时,对象内部的setInterval是否可以防止垃圾回收?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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