whatwg / dom

DOM Standard
https://dom.spec.whatwg.org/
Other
1.58k stars 294 forks source link

Methods on ChildNode and ParentNode that take `(Node or DOMString)... nodes` should not use an intermediate DocumentFragment #1313

Open dbaron opened 1 month ago

dbaron commented 1 month ago

What is the issue with the DOM Standard?

There are a bunch of methods on ChildNode and ParentNode that take a (Node or DOMString)... nodes argument. The specification text for these methods uses the converting nodes into a node algorithm, which temporarily moves the nodes into a DocumentFragment, and then these nodes are later moved to their final destination.

This is inefficient because it runs the insertion steps and removing steps for all the elements in the subtree an extra time, which involves an extra two traversals of the subtree and some additional work for the steps.

This has been optimized away in WebKit and I'm working on a similar optimization in Chromium. While I think it's doable to make these optimizations pass existing tests and not break existing Web content (WebKit has already shown this), I think the differences are almost certainly observable in various ways, including the states things get left in in various failure cases (e.g., when a node in the middle of the list can't be inserted).

While the current specification is convenient and simple, I think it would probably be better to describe the optimized behavior in the DOM specification, even though it's more complex, since the faster performance does serve end users better, and having better interoperability on the faster behavior would serve both users and developers even if it's more work for specification authors and implementers.

There are probably some interesting tradeoffs we can make in the process that make tradeoffs between (a) compatibility with existing content, (b) compatibility with the existing specified behavior (which may be different from (a)), (c) having a model that is generally consistent and (d) having a model that does reasonable things on errors, and (e) having a model that offers consistent behavior between specifying a single node and specifying multiple nodes (which I suspect the current specification text does not fully do, although it does try).

annevk commented 1 month ago

Yeah, that sounds reasonable. I guess we need some tests for the obscure cases too to decide what to do.

cc @rniwa

dbaron commented 1 month ago

Also cc @smaug----

dbaron commented 1 month ago

Oh, and one other edge case is whether these methods accept DocumentType nodes when changing the children of a Document. (This is because DocumentType nodes are not allowed as a child of a DocumentFragment.)

smaug---- commented 1 month ago

Looks like the algorithms in DOM could almost handle this. Need to be careful with MutationRecords.