Weak Reference proposal
Jonas Sicking
jonas at sicking.cc
Wed Feb 17 08:41:23 UTC 2016
On Tue, Feb 16, 2016 at 11:02 PM, Domenic Denicola <d at domenic.me> wrote:
>> For each NodeIterator object iterator whose root’s node document is node’s node document, run the NodeIterator pre-removing steps given node and iterator.
>
> Rephrased: every time you remove a Node from a document, you must go through all of the document's NodeIterators and run some cleanup steps (which have the effect of changing observable properties and behavior of the NodeIterator).
Could you implement all of this using MutationObservers? I.e. have the
NodeIterators observe the relevant nodes using MutationObservers?
The only case that I can think of where the DOM could use weak
references is for the getElementsByTagName(x) function. This function
will either return a new NodeList object, or an existing one. The
reason it sometimes returns an existing one is for performance
reasons. We saw a lot of code doing:
var i;
for (i = 0; i < document.getElementsByTagName("div").length; i++) {
var elem = document.getElementsByTagName("div")[i];
doStuffWith(elem);
}
This generated a ton of NodeList objects, which are expensive to
allocate. Hence browsers started caching these objects and returned an
existing object "sometimes".
The gecko implementation of "sometimes" uses a hash map keyed on
tagname containing weak references to the returned NodeList. This is
observable by for example doing:
document.getElementsByTagName("div").foopy = "foopy";
if (document.getElementsByTagName("div").foopy != "foopy") {
// GC ran between the getElementsByTagName calls.
}
However this exact behavior is not defined by spec. But I believe that
all major browsers do do something similar for performance reasons.
(This API is as old as it is crummy. And it is no surprise that it is
poorly used).
But it likely would be possible to write an implementation of
"sometimes" which doesn't use weak references, at the cost of higher
memory usage.
/ Jonas
More information about the es-discuss
mailing list