Repository navigation
🐛 fix(dom): keep text writes from storing every assigned value - #2133
Conversation
Assigning Text.data or Comment.data, or the etree text and tail properties, copied the new value into a fresh arena buffer on every call. The arena frees nothing until the tree is released, so code that grows a text one piece at a time, such as the lxml idiom of handing each removed element's tail to its neighbour, kept every intermediate value and used memory that grows with the square of the final text. The same held for normalize() after each append. Each character-data node now keeps the capacity of its buffer in the byte insert_text already uses for that. A write that fits goes into the node's own buffer; one that does not takes a buffer of double the size, so a run of writes allocates a small multiple of its largest value. The first new buffer stays exact, so a node written once uses what it used before. The etree setters write into the first Text node of the run instead of replacing it, so they reach the same path. A buffer shared with a parser clone loses its capacity, and so do one replaced by whitespace collapsing and one a Range edit narrows or splits, so no write lands in memory another node reads or past the end of its buffer. Fixes tox-dev#1760
Merging this PR will improve performance by 33.33%2 warnings
Performance Changes
Tip Curious why performance improved? Comment Comparing Footnotes
|
Writing
Text.dataorComment.datamany times kept every intermediate value in the document's memory. The arena frees nothing until the tree is dropped, so code that builds a text one piece at a time used memory that grew with the square of the final text. Moving each removed element's tail into the text before it was one such pattern, and callingnormalize()after each append was another. 🧠 After this change a node reuses one buffer that grows by doubling, so memory tracks the text the node holds now.Architecture
Each text node keeps its text in one buffer and records the capacity of that buffer. A write that fits is copied into the node's own buffer, and a write that does not fit takes a buffer twice the old capacity, so a run of writes allocates a constant multiple of its largest value.
normalize()merges into the first Text node through the same path.The etree
textandtailsetters update the first Text node of a run instead of replacing it. Any place that shares a buffer or moves a node's view into it drops the capacity, so only a buffer the node alone writes is reused.Behavior changes
textandtailsetters update the existing first Text node instead of inserting a new one. ATextobject held from before the assignment shows the new value, and aMutationObserverrecords acharacterDatachange for that node instead of achildListchange.Fixes #1760.