Never turn off MutationObserver

Is it wrong to disable MutationObserver?

I am monitoring new elements added to the DOM, but I never perform an explicit disconnect. Could this cause memory problems?

+6
source share
1 answer

If you need your MutationObserver only once (for example, for initialization or something else), you should disable it after it is no longer used. This may or may not free some memory, but it will certainly reduce CPU utilization.

If your MutationObserver is necessary for the normal functioning of your website and it will need to be disabled only when the user closes the tab or window, I would say that disconnection is not required, since the browser must clear anyway. I mean, you could unregister event handlers, but no one does. And, of course, no one removes all their functions and variables, they expect the browser to do this.
It might even be faster not to disable your MutationObserver, since the cleanup code (almost certainly) is written in machine code, which runs much faster than JavaScript. The difference would most likely be inconspicuous, though.

And since you specifically ask

Could this cause memory problems?

Yes, it can create a memory leak. But this way you can declare a variable if the browser does not perform the corresponding cleaning, which will be an error in this browser.
Suppose you are using a reasonable environment, but you should be fine without turning off your MO.

+1
source

Source: https://habr.com/ru/post/985349/


All Articles