admin管理员组文章数量:1325409
Is it bad to not disconnect a MutationObserver?
I'm performing an observation for new elementes added to the DOM, but I'm never performing an explicit disconnection. Could this cause memory issues?
Is it bad to not disconnect a MutationObserver?
I'm performing an observation for new elementes added to the DOM, but I'm never performing an explicit disconnection. Could this cause memory issues?
Share Improve this question edited Dec 15, 2022 at 16:02 Ranjeet Eppakayala 3,0581 gold badge13 silver badges23 bronze badges asked Apr 17, 2015 at 13:22 Matías CánepaMatías Cánepa 5,9844 gold badges61 silver badges108 bronze badges 2- You mean, you need your MutationObserver to do stuff for the entire duration of the website being viewed? – Siguza Commented Apr 17, 2015 at 13:28
- @Siguza at least while certain jQuery is open using this feature – Matías Cánepa Commented Apr 17, 2015 at 13:30
1 Answer
Reset to default 8If you need your MutationObserver only once (e.g. for initialization or whatever), you should disconnect it after it's no longer used. This might or might not free some memory, but it will certainly decrease CPU load.
If your MutationObserver is required for the normal functioning of your website and would only have to be disconnected when the user closes their tab or window, I would say disconnecting is not required, as the browser has to clean up anyway. I mean, you could unregister event handlers as well, but no-one really does that. And certainly no-one deletes all their functions and variables, they expect the browser to do that.
It might even be faster to not disconnect your MutationObserver, as the cleanup code is (almost certainly) written in machine code, which executes much faster than JavaScript. The difference would most likely be unnoticeable though.
And since you specifically ask
Could this cause memory issues?
Yes, it could create a memory leak. But so could declaring a variable, if the browser does not perform appropriate cleanup, which would be a bug in that browser.
Assuming a sane environment though, you should be fine without disconnecting your MO.
本文标签: javascriptIs it bad to not disconnect a MutationObserverStack Overflow
版权声明:本文标题:javascript - Is it bad to not disconnect a MutationObserver? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742190075a2430046.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论