Skip to content

Commit 1767909

Browse files
Make :nth-* pseudo-classes linear on wide sibling lists (#119)
* Index sibling lists once per query for the :nth-* pseudo-classes isNthChild() walked the preceding (or following) siblings of every candidate, so matching n siblings cost n^2/2 hops. Positions are now recorded for a whole sibling list on first use and remembered until the outermost DOMTraverser::find() ends, so a DOM mutated between queries is never answered from a stale index. Nested :not()/:has() queries, and the per-element queries run by filter() and children(), share the outer handler so they reuse the same index instead of rebuilding it per candidate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Share the sibling index across NodeMatcher's per-node queries NodeMatcher::matches() runs a traverser per node for the walk-and-stop methods, so each got its own handler and indexed the whole sibling list to answer one node: nextUntil(':nth-last-child(1)') over 2000 siblings went from 290 ms on main to 950 ms. The matcher now holds one handler open for its lifetime, which is already a single call (17 ms). Outside a query the index is built into a throwaway store, replacing the separate sibling walkers, and entries are flat arrays. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 355753f commit 1767909

6 files changed

Lines changed: 303 additions & 53 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ QueryPath Changelog
3434
- Fix `QPXML::pi($prefix)` always returning `NULL` with an "Undefined property" warning instead of the matching processing instruction's text (issue #79)
3535
- Fix fatal error when running a CSS selector against a match set that contains non-element nodes (text, comment, CDATA or processing instruction), as `contents()` returns. Those nodes now simply do not match, instead of calling element-only DOM methods on them
3636
- Fix fatal error in `attr()`, `addClass()`, `removeClass()`, `css()`, `hasClass()`, `hasAttr()` and `removeAttr()` when the match set contains non-element nodes (text, comment, CDATA or processing instruction), as `contents()` returns (issue #98). As in jQuery, those nodes are skipped, and the `attr()` and `css()` getters return `NULL` when the first match is not an element
37+
- Fix `:nth-child()`, `:nth-last-child()`, `:nth-of-type()` and `:nth-last-of-type()` taking quadratic time on wide sibling lists (issue #84). Each sibling list is now indexed once per query, shared with nested `:not()` and `:has()` queries and across the per-element tests that `closest()`, `nextUntil()` and the other walk-and-stop methods run, instead of being walked for every element. `tr:nth-child(2n)` on a 4000-row table drops from about 320 ms to 4 ms
3738
- Fix `find('a > b')` throwing a `TypeError` when the left-hand side matched the root element, whose parent is the document rather than an element
3839
- Fix `QPXML::createElement()` emitting an "Only variables should be passed by reference" notice for a namespace-prefixed element name without an explicit namespace URI (issue #82)
3940
- Fix the `:text` pseudo-class so it matches jQuery: it selects `input` elements whose `type` attribute is absent or is `text` (case-insensitively). It never indicated, and still does not indicate, whether a node is a text node

‎src/CSS/DOMTraverser.php‎

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -105,10 +105,16 @@ class DOMTraverser implements Traverser
105105
* @param SplObjectStorage $splos
106106
* @param bool $initialized
107107
* @param null $scopeNode
108+
* @param PseudoClass|null $psHandler
109+
* Share an outer query's handler, so a nested query reuses its sibling index.
108110
*/
109-
public function __construct(SplObjectStorage $splos, bool $initialized = false, $scopeNode = null)
110-
{
111-
$this->psHandler = new PseudoClass();
111+
public function __construct(
112+
SplObjectStorage $splos,
113+
bool $initialized = false,
114+
$scopeNode = null,
115+
?PseudoClass $psHandler = null
116+
) {
117+
$this->psHandler = $psHandler ?? new PseudoClass();
112118
$this->initialized = $initialized;
113119

114120
// Re-use the initial splos
@@ -167,15 +173,19 @@ public function find($selector): DOMTraverser
167173
//$selector = $handler->toArray();
168174
$found = $this->newMatches();
169175
$isFiltered = false;
170-
foreach ($handler as $selectorGroup) {
171-
if ($this->groupIsSetFiltered($selectorGroup)) {
172-
$isFiltered = true;
173-
}
176+
$this->psHandler->beginQuery();
177+
try {
178+
foreach ($handler as $selectorGroup) {
179+
if ($this->groupIsSetFiltered($selectorGroup)) {
180+
$isFiltered = true;
181+
}
174182

175-
foreach ($this->resolveGroup($selectorGroup) as $candidate) {
176-
// $this->debug('Attaching ' . $candidate->nodeName);
177-
$found->offsetSet($candidate);
183+
foreach ($this->resolveGroup($selectorGroup) as $candidate) {
184+
$found->offsetSet($candidate);
185+
}
178186
}
187+
} finally {
188+
$this->psHandler->endQuery();
179189
}
180190

181191
// Comma-separated groups are filtered independently (as in jQuery), so the
@@ -326,7 +336,7 @@ protected function applySetFilter(array $nodes, array $pseudoClass): array
326336
return [];
327337
}
328338

329-
$traverser = new self($this->toMatches($nodes), true, $this->scopeNode);
339+
$traverser = new self($this->toMatches($nodes), true, $this->scopeNode, $this->psHandler);
330340
$inner = $traverser->find($value)->matches();
331341

332342
$filtered = [];

‎src/CSS/DOMTraverser/PseudoClass.php‎

Lines changed: 68 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use QueryPath\CSS\NotImplementedException;
1818
use QueryPath\CSS\EventHandler;
1919
use QueryPath\CSS\ParseException;
20+
use DOMNode;
2021
use SPLObjectStorage;
2122

2223
/**
@@ -26,6 +27,51 @@
2627
class PseudoClass
2728
{
2829

30+
/**
31+
* Element positions within their sibling lists, keyed by element.
32+
*
33+
* Each entry is [fromStart, fromEnd, ofTypeFromStart, ofTypeFromEnd].
34+
* Positions are only kept while a query is running: the DOM may be mutated
35+
* between queries, so they must not outlive the query that indexed them.
36+
*
37+
* @var SplObjectStorage|null
38+
*/
39+
protected $positions;
40+
41+
/**
42+
* How many queries (including nested :not() and :has() queries) are running.
43+
*
44+
* @var int
45+
*/
46+
protected $queryDepth = 0;
47+
48+
/**
49+
* Parsed an+b rules, keyed by the rule string.
50+
*
51+
* @var array
52+
*/
53+
protected $anbRules = [];
54+
55+
/**
56+
* Start remembering sibling positions, so the :nth-* pseudo-classes index
57+
* each sibling list once rather than walking it for every element.
58+
*
59+
* Calls nest; positions are forgotten when the outermost query ends.
60+
*/
61+
public function beginQuery(): void
62+
{
63+
if ($this->queryDepth++ === 0) {
64+
$this->positions = new SplObjectStorage();
65+
}
66+
}
67+
68+
public function endQuery(): void
69+
{
70+
if (--$this->queryDepth === 0) {
71+
$this->positions = null;
72+
}
73+
}
74+
2975
/**
3076
* Tests whether the given element matches the given pseudoclass.
3177
*
@@ -352,7 +398,7 @@ protected function has($node, $selector): bool
352398
{
353399
$splos = new SPLObjectStorage();
354400
$splos->offsetSet($node);
355-
$traverser = new DOMTraverser($splos, true);
401+
$traverser = new DOMTraverser($splos, true, null, $this);
356402
$results = $traverser->find($selector)->matches();
357403

358404
return count($results) > 0;
@@ -369,42 +415,24 @@ protected function isNot($node, $selector): bool
369415
}
370416

371417
/**
372-
* Get the relative position of a node in its sibling set.
418+
* Record the position of every element child of $parent.
373419
*/
374-
protected function nodePositionFromStart($node, $byType = false): int
420+
protected function indexSiblings(DOMNode $parent, SplObjectStorage $positions): void
375421
{
376-
$i = 1;
377-
$tag = $node->tagName;
378-
while (isset($node->previousSibling)) {
379-
$node = $node->previousSibling;
380-
if ($node->nodeType === XML_ELEMENT_NODE && ( ! $byType || $node->tagName === $tag)) {
381-
++$i;
422+
$elements = [];
423+
$typeCounts = [];
424+
foreach ($parent->childNodes as $child) {
425+
if ($child->nodeType === XML_ELEMENT_NODE) {
426+
$tag = $child->tagName;
427+
$typeCounts[$tag] = ($typeCounts[$tag] ?? 0) + 1;
428+
$elements[] = [$child, $typeCounts[$tag]];
382429
}
383430
}
384431

385-
return $i;
386-
}
387-
388-
/**
389-
* Get the relative position of a node in its sibling set.
390-
*
391-
* @param $node
392-
* @param bool $byType
393-
*
394-
* @return int
395-
*/
396-
protected function nodePositionFromEnd($node, $byType = false): int
397-
{
398-
$i = 1;
399-
$tag = $node->tagName;
400-
while (isset($node->nextSibling)) {
401-
$node = $node->nextSibling;
402-
if ($node->nodeType === XML_ELEMENT_NODE && ( ! $byType || $node->tagName === $tag)) {
403-
++$i;
404-
}
432+
$count = count($elements);
433+
foreach ($elements as $i => [$child, $typePos]) {
434+
$positions[$child] = [$i + 1, $count - $i, $typePos, $typeCounts[$child->tagName] - $typePos + 1];
405435
}
406-
407-
return $i;
408436
}
409437

410438
/**
@@ -433,7 +461,10 @@ protected function nodePositionFromEnd($node, $byType = false): int
433461
*/
434462
protected function isNthChild($node, $value, $reverse = false, $byType = false): bool
435463
{
436-
[$groupSize, $elementInGroup] = Util::parseAnB($value);
464+
if (! isset($this->anbRules[$value])) {
465+
$this->anbRules[$value] = Util::parseAnB($value);
466+
}
467+
[$groupSize, $elementInGroup] = $this->anbRules[$value];
437468
$parent = $node->parentNode;
438469
if (empty($parent)
439470
|| ($groupSize === 0 && $elementInGroup === 0)
@@ -442,11 +473,12 @@ protected function isNthChild($node, $value, $reverse = false, $byType = false):
442473
}
443474

444475
// First we need to find the position of $node in other elements.
445-
if ($reverse) {
446-
$pos = $this->nodePositionFromEnd($node, $byType);
447-
} else {
448-
$pos = $this->nodePositionFromStart($node, $byType);
476+
// Outside a query nothing is remembered, so index into a throwaway store.
477+
$positions = $this->positions ?? new SplObjectStorage();
478+
if (! $positions->offsetExists($node)) {
479+
$this->indexSiblings($parent, $positions);
449480
}
481+
$pos = $positions[$node][($byType ? 2 : 0) + ($reverse ? 1 : 0)];
450482

451483
// If group size is 0, we just check to see if this
452484
// is the nth element:

‎src/Helpers/NodeMatcher.php‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use DOMNode;
66
use QueryPath\CSS\DOMTraverser;
7+
use QueryPath\CSS\DOMTraverser\PseudoClass;
78
use QueryPath\CSS\ParseException;
89
use SplObjectStorage;
910

@@ -20,9 +21,9 @@
2021
* would be the only member of its own one-element set.
2122
*
2223
* matches() remembers each per-node answer, because the walk-and-stop traversals
23-
* (closest(), nextUntil(), ...) revisit the same nodes from every starting element. An
24-
* instance must not outlive the call that made it, or a later DOM change could leave it
25-
* holding stale answers.
24+
* (closest(), nextUntil(), ...) revisit the same nodes from every starting element, and
25+
* every query shares one sibling index for the :nth-* pseudo-classes. An instance must not
26+
* outlive the call that made it, or a later DOM change could leave it holding stale answers.
2627
*/
2728
final class NodeMatcher
2829
{
@@ -37,6 +38,11 @@ final class NodeMatcher
3738
*/
3839
private $results;
3940

41+
/**
42+
* @var PseudoClass
43+
*/
44+
private $psHandler;
45+
4046
/**
4147
* @param string $selector
4248
* A valid CSS selector.
@@ -45,6 +51,10 @@ public function __construct($selector)
4551
{
4652
$this->selector = $selector;
4753
$this->results = new SplObjectStorage();
54+
55+
// Held open for the matcher's lifetime, which is a single call.
56+
$this->psHandler = new PseudoClass();
57+
$this->psHandler->beginQuery();
4858
}
4959

5060
/**
@@ -124,7 +134,7 @@ public function matching(SplObjectStorage $nodes): SplObjectStorage
124134
// than seeding them with a descendant search. The scope node is left at its default (the
125135
// document element) so that `:scope` means the same here as in find(); scoping to a
126136
// candidate would make every candidate match `:scope`.
127-
$traverser = new DOMTraverser($nodes, true);
137+
$traverser = new DOMTraverser($nodes, true, null, $this->psHandler);
128138

129139
return $traverser->find($this->selector)->matches();
130140
}

‎tests/QueryPath/CSS/DOMTraverserTest.php‎

Lines changed: 109 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,14 @@ public function testConstructor()
3737
$this->assertInstanceOf('\QueryPath\CSS\DOMTraverser', $traverser);
3838
}
3939

40-
protected function traverser()
40+
protected function traverser($xml = null)
4141
{
4242
$dom = new DOMDocument('1.0');
43-
$dom->load($this->xml_file);
43+
if ($xml === null) {
44+
$dom->load($this->xml_file);
45+
} else {
46+
$dom->loadXML($xml);
47+
}
4448

4549
$splos = new SPLObjectStorage();
4650
$splos->offsetSet($dom->documentElement);
@@ -368,4 +372,107 @@ public function testMultipleSelectors()
368372
$matches = $this->find('one, two');
369373
$this->assertEquals(2, count($matches));
370374
}
375+
376+
/**
377+
* The <ul> children are, by position: l1 p1 l2 l3 p2 l4 l5 p3.
378+
*/
379+
protected $nthXml = '<?xml version="1.0"?><root><ul id="ul">'
380+
. 'text<!-- comment --><li id="l1"/><p id="p1"/><li id="l2"/><!-- comment --><li id="l3"/>'
381+
. 'text<p id="p2"/><li id="l4"/><li id="l5"/><p id="p3"/>text'
382+
. '</ul><ol id="ol"><li id="o1"/><li id="o2"/></ol></root>';
383+
384+
protected function ids($nodes): array
385+
{
386+
$ids = [];
387+
foreach ($nodes as $node) {
388+
$ids[] = $node->getAttribute('id');
389+
}
390+
391+
return $ids;
392+
}
393+
394+
public function nthPseudoClassProvider(): array
395+
{
396+
return [
397+
// :nth-child()
398+
['ul > :nth-child(odd)', ['l1', 'l2', 'p2', 'l5']],
399+
['ul > :nth-child(even)', ['p1', 'l3', 'l4', 'p3']],
400+
['ul > :nth-child(n)', ['l1', 'p1', 'l2', 'l3', 'p2', 'l4', 'l5', 'p3']],
401+
['ul > :nth-child(3)', ['l2']],
402+
['ul > :nth-child(-n+3)', ['l1', 'p1', 'l2']],
403+
['ul > :nth-child(3n-5)', ['l1', 'l3', 'l5']],
404+
['ul > :nth-child(0n+0)', []],
405+
['ul > :nth-child(-2n-1)', []],
406+
['ul > :nth-child(9)', []],
407+
['li:nth-child(2n+1)', ['l1', 'l2', 'l5', 'o1']],
408+
409+
// :nth-last-child()
410+
['ul > :nth-last-child(1)', ['p3']],
411+
['ul > :nth-last-child(odd)', ['p1', 'l3', 'l4', 'p3']],
412+
['ul > :nth-last-child(-n+2)', ['l5', 'p3']],
413+
['ul > :nth-last-child(8)', ['l1']],
414+
['li:nth-last-child(2)', ['l5', 'o1']],
415+
416+
// :nth-of-type(). The <li> are l1-l5 and the <p> p1-p3.
417+
['li:nth-of-type(odd)', ['l1', 'l3', 'l5', 'o1']],
418+
['p:nth-of-type(2)', ['p2']],
419+
['ul > :nth-of-type(2)', ['l2', 'p2']],
420+
['ul > :nth-of-type(-n+1)', ['l1', 'p1']],
421+
['ul > :nth-of-type(4)', ['l4']],
422+
423+
// :nth-last-of-type()
424+
['li:nth-last-of-type(1)', ['l5', 'o2']],
425+
['ul > :nth-last-of-type(2)', ['p2', 'l4']],
426+
['p:nth-last-of-type(n+2)', ['p1', 'p2']],
427+
['ul > :nth-last-of-type(3n)', ['p1', 'l3']],
428+
429+
// Several :nth-* in one query share the same sibling index.
430+
['li:nth-child(odd):nth-of-type(odd)', ['l1', 'l5', 'o1']],
431+
['ul > :nth-child(even):nth-last-of-type(1)', ['p3']],
432+
['ul > :nth-child(1), ul > :nth-last-child(1)', ['l1', 'p3']],
433+
434+
// Nested queries.
435+
['ul > :not(:nth-child(odd))', ['p1', 'l3', 'l4', 'p3']],
436+
['ul > :not(:nth-last-of-type(-n+2))', ['l1', 'p1', 'l2', 'l3']],
437+
];
438+
}
439+
440+
/**
441+
* @dataProvider nthPseudoClassProvider
442+
*/
443+
public function testNthPseudoClasses($selector, array $expected)
444+
{
445+
$this->assertSame($expected, $this->ids($this->traverser($this->nthXml)->find($selector)->matches()));
446+
}
447+
448+
public function testNthPseudoClassesInFilterAndChildren()
449+
{
450+
$this->assertSame(['l1', 'l2', 'p2', 'l5'], $this->ids(qp($this->nthXml, 'ul > *')->filter(':nth-child(odd)')->get()));
451+
$this->assertSame(['l5', 'p3'], $this->ids(qp($this->nthXml, 'ul')->children(':nth-last-of-type(1)')->get()));
452+
$this->assertSame(['l2', 'o2'], $this->ids(qp($this->nthXml, 'ul, ol')->children('li:nth-of-type(2)')->get()));
453+
}
454+
455+
/**
456+
* Sibling positions are indexed per query, so querying again after the DOM
457+
* changes must see the new positions.
458+
*/
459+
public function testNthPseudoClassesAfterMutation()
460+
{
461+
$qp = qp('<?xml version="1.0"?><root><li id="a"/><li id="b"/><li id="c"/></root>');
462+
463+
$this->assertSame(['b'], $this->ids($qp->find('li:nth-child(2)')->get()));
464+
$this->assertSame(['b'], $this->ids($qp->find('li:nth-last-of-type(2)')->get()));
465+
466+
$qp->find('root')->prepend('<li id="new"/>')->append('<p/>');
467+
468+
$this->assertSame(['a'], $this->ids($qp->find('li:nth-child(2)')->get()));
469+
$this->assertSame(['c'], $this->ids($qp->find('li:nth-last-child(2)')->get()));
470+
$this->assertSame(['a'], $this->ids($qp->find('li:nth-of-type(2)')->get()));
471+
$this->assertSame(['b'], $this->ids($qp->find('li:nth-last-of-type(2)')->get()));
472+
473+
$qp->find('#b')->remove();
474+
475+
$this->assertSame(['c'], $this->ids($qp->find('li:nth-child(3)')->get()));
476+
$this->assertSame(['new', 'c'], $this->ids($qp->find('li:nth-child(odd)')->get()));
477+
}
371478
}

0 commit comments

Comments
 (0)