Skip to content

Commit 027f21e

Browse files
miss-islingtonsethmlarsonjacobtylerwalls
authored
[3.14] gh-142145: Remove quadratic behavior in node ID cache clearing (GH-142146) (#142209)
gh-142145: Remove quadratic behavior in node ID cache clearing (GH-142146) * Remove quadratic behavior in node ID cache clearing * Add news fragment --------- (cherry picked from commit 08d8e18) Co-authored-by: Seth Michael Larson <seth@python.org> Co-authored-by: Jacob Walls <38668450+jacobtylerwalls@users.noreply.github.com>
1 parent 79245a4 commit 027f21e

File tree

3 files changed

+20
-8
lines changed

3 files changed

+20
-8
lines changed

Lib/test/test_minidom.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import copy
44
import pickle
5+
import time
56
import io
67
from test import support
78
import unittest
@@ -173,6 +174,23 @@ def testAppendChild(self):
173174
self.assertEqual(dom.documentElement.childNodes[-1].data, "Hello")
174175
dom.unlink()
175176

177+
def testAppendChildNoQuadraticComplexity(self):
178+
impl = getDOMImplementation()
179+
180+
newdoc = impl.createDocument(None, "some_tag", None)
181+
top_element = newdoc.documentElement
182+
children = [newdoc.createElement(f"child-{i}") for i in range(1, 2 ** 15 + 1)]
183+
element = top_element
184+
185+
start = time.time()
186+
for child in children:
187+
element.appendChild(child)
188+
element = child
189+
end = time.time()
190+
191+
# This example used to take at least 30 seconds.
192+
self.assertLess(end - start, 1)
193+
176194
def testAppendChildFragment(self):
177195
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
178196
dom.documentElement.appendChild(frag)

Lib/xml/dom/minidom.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -292,13 +292,6 @@ def _append_child(self, node):
292292
childNodes.append(node)
293293
node.parentNode = self
294294

295-
def _in_document(node):
296-
# return True iff node is part of a document tree
297-
while node is not None:
298-
if node.nodeType == Node.DOCUMENT_NODE:
299-
return True
300-
node = node.parentNode
301-
return False
302295

303296
def _write_data(writer, text, attr):
304297
"Writes datachars to writer."
@@ -1555,7 +1548,7 @@ def _clear_id_cache(node):
15551548
if node.nodeType == Node.DOCUMENT_NODE:
15561549
node._id_cache.clear()
15571550
node._id_search_stack = None
1558-
elif _in_document(node):
1551+
elif node.ownerDocument:
15591552
node.ownerDocument._id_cache.clear()
15601553
node.ownerDocument._id_search_stack= None
15611554

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove quadratic behavior in ``xml.minidom`` node ID cache clearing.

0 commit comments

Comments
 (0)