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

Let me better explain with a use case:

## Use Case:

I would like to observe an entire SVG DOM tree. Whenever anything in the tree changes, I want to map those changes to changes in a WebGL scene graph tree (f.e. create with a 2D library like Two.js or Pixi.js).

The result is an SVG DOM that can be manipulated (f.e. animated) and the result rendered in WebGL rather than the browser's implementation. It is easy to apply certain optimizations this way (because we can't touch the browser implementation).

I need to observe attribute changes and also observe when any nodes are added or removed anywhere in the tree.

## first approach

I could make a single MutationObserver, then I can traverse the SVG tree and observe every element in the tree. I want to observe attribute changes, and children being added and removed. For children added/removed, I would never use `subtree: true`, only `childList: true`.

If a child is removed, I need to stop observing it (uh oh).

I would have to `disconnect()` the single MutationObserver, then traverse the whole tree again and start observing everything again.

Ouch.

## second approach

I could make a single MutationObserver observing only the root `<svg>` element using `subtree: true`. When the observer callback is fired, I would have to analyze the list of mutation records to determine the net changes of the whole tree.

This defeats the purpose of having a mutation record list, because I will simply prefer to use a DOM-diffing library inside the callback to determine net changes in the whole SVG tree.

The bigger the SVG tree, the more CPU and Memory intensive this will be.

But at least I know I can easily *not* leak memory.

## third approach

Just like the first approach, except instead of one MutationObserver observing every node, I would have one MutationObserver per node for every node.

The rest is the same, except I now have the ability to stop observing certain nodes when they are no longer in the tree.

## fourth (ideal, not-yet-possible) approach

Instantiating a single MutationObserver then having it observe all the element in the SVG seems like it would be the most light weight, but it takes big effort not to leak memory.

If we had API to stop observing specific nodes, then this approach would be just like the first, except it would be very easy to stop observing nodes that are no longer in the SVG tree.

-- 
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#issuecomment-318225143

Received on Thursday, 27 July 2017 00:53:09 UTC