Repository navigation
🐛 fix(dom): keep Range calls over a wide child list linear - #2144
Conversation
A Range offset is a child index, and the tree keeps children in a linked list. Every Range call that turned a child into its offset or an offset into its child walked the siblings from the first child: the boundary setters, select_node, the point and boundary comparisons, the offset validation, the child count, the contained-run scan, and the offset lookups in insert_node and surround_contents. A program that calls one of these once per child of a wide element, such as a highlighter wrapping each text node of one paragraph, took time quadratic in the child count. The tree handle now keeps four (parent, child, index) cursors, modelled on the etree view cursors. A lookup walks from the node toward the first child and, in step, both ways toward the cursors of the same parent, so a loop in either direction over one child list takes a step per call. The edits Range makes itself move the cursors with each insertion and removal, so its own content operations keep them. Edits through other APIs bump mutation_version, and normalize unlinks without one, so either clears them. Code that never uses a Range pays only for the larger handle. Fixes tox-dev#1743
Merging this PR will improve performance by 77.87%2 warnings
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
Range methods that map a child to its offset, or an offset to its child, walked the sibling list from the first child on every call. 📏 A loop that calls a Range method once per child of a wide element, such as a highlighter that wraps each text node of one paragraph, therefore ran in quadratic time. After this change a loop over one child list takes a constant number of steps per call, in either direction.
Architecture
The tree handle keeps a few sibling cursors, each one a parent, a child and an index. A lookup starts from the cursor nearest its target, and a loop keeps a cursor one step behind it. Range's own edits shift the cursors they touch. An edit made through any other API, or
normalize(), empties them, using the handle's mutation version and a count of unlinks.Storing a rank in every node would also give constant-time offsets, but renumbering on each insertion moves the quadratic cost into tree building, and an order-statistic tree slows every child-list mutation. The cursors cost nothing outside Range calls.
Behavior changes
Fixes #1743