Skip to content

Commit f4eb9ab

Browse files
sethmlarsonjacobtylerwalls
authored andcommitted
pythongh-142145: Remove quadratic behavior in node ID cache clearing (pythonGH-142146)
* Remove quadratic behavior in node ID cache clearing Co-authored-by: Jacob Walls <38668450+jacobtylerwalls@users.noreply.github.com> * 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 1173f80 commit f4eb9ab

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
@@ -177,6 +178,23 @@ def testAppendChild(self):
177178
self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
178179
dom.unlink()
179180

181+
def testAppendChildNoQuadraticComplexity(self):
182+
impl = getDOMImplementation()
183+
184+
newdoc = impl.createDocument(None, "some_tag", None)
185+
top_element = newdoc.documentElement
186+
children = [newdoc.createElement(f"child-{i}") for i in range(1, 2 ** 15 + 1)]
187+
element = top_element
188+
189+
start = time.time()
190+
for child in children:
191+
element.appendChild(child)
192+
element = child
193+
end = time.time()
194+
195+
# This example used to take at least 30 seconds.
196+
self.assertLess(end - start, 1)
197+
180198
def testAppendChildFragment(self):
181199
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
182200
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, data):
304297
"Writes datachars to writer."
@@ -1539,7 +1532,7 @@ def _clear_id_cache(node):
15391532
if node.nodeType == Node.DOCUMENT_NODE:
15401533
node._id_cache.clear()
15411534
node._id_search_stack = None
1542-
elif _in_document(node):
1535+
elif node.ownerDocument:
15431536
node.ownerDocument._id_cache.clear()
15441537
node.ownerDocument._id_search_stack= None
15451538

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)