[whatwg/dom] MutationObserver opportunity for memory leak. (#482)

There's a problem with MutationObserver.

**1)** Suppose we want to use [one MutationObserver to observe multiple elements](https://stackoverflow.com/questions/30807846/can-a-single-mutationobserver-object-observe-multiple-targets).

There's no way to stop observing just one of the observed elements. The `MutationObserver.prototype.disconnect()` method only allows us to stop observing *all* elements.

Therefore, when using a single MutationObserver to try and observe multiple elements in a tree, if one of those elements is permanently removed, there's no clean way to stop observing only that node while still observing other nodes.

This means that a naive developer (there's many *many* beginner programmers in the web) will never call `disconnect()`, and the observed node may stay in (leak into) memory.

---

**2)** Another approach is to use a single MutationObserver on the root node of a tree, with `subtree: true`, then in the callback try to determine the net changes that occurred in the whole tree, but this is [very difficult](https://stackoverflow.com/questions/38998599), and essentially requires one to write error-prone logic to reduce mutation records in the set of net changes in the tree, which ultimately leads to one simply ignoring the list of mutation records and using a DOM-diffing library.

The benefit of this approach is less likelihood for leaky code, `disconnect()` required to be called only when the root node is no longer needed to be observed.

---

**3)** Another approach is to use one MutationObserver per node-to-be-observed, and never use `subtree: true`, only `childList: true`. This can also be very tricky, and requires some significant code in order to call `disconnect` on every MutationObserver when the node no longer needs to be observed.

The downside of this approach is higher CPU and Memory usage due to the need for one MutationObserver per observed node.

The result is the same as the first approach, but with this approach cleanup is straight forward, less likelihood for leaks.

---

## Solution:

The simplest approach would be if `MutationObserver.prototype` had an `unobserve(node)` method. Or perhaps a node could be passed into `disconnect(node)`. We would be able to stop listening to specific nodes that way. 

The benefit would be the flexibility of approach **3)** but without the extra CPU and Memory overhead.

-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/whatwg/dom/issues/482

Received on Thursday, 27 July 2017 00:20:16 UTC