Matías Cánepa
Matías Cánepa

Reputation: 5974

Is it bad to not disconnect a MutationObserver?

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?

Upvotes: 9

Views: 4135

Answers (1)

Siguza
Siguza

Reputation: 23830

If 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.

Upvotes: 8

Related Questions