Skip to content

Commit 21f088b

Browse files
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>
1 parent a321961 commit 21f088b

4 files changed

Lines changed: 28 additions & 65 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +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 queries `filter()` and `children()` 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
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
3838
- 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
3939
- 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)
4040
- 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/PseudoClass.php‎

Lines changed: 11 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ class PseudoClass
3030
/**
3131
* Element positions within their sibling lists, keyed by element.
3232
*
33-
* Each entry is [[fromStart, fromEnd], [ofTypeFromStart, ofTypeFromEnd]].
33+
* Each entry is [fromStart, fromEnd, ofTypeFromStart, ofTypeFromEnd].
3434
* Positions are only kept while a query is running: the DOM may be mutated
3535
* between queries, so they must not outlive the query that indexed them.
3636
*
@@ -60,7 +60,9 @@ class PseudoClass
6060
*/
6161
public function beginQuery(): void
6262
{
63-
++$this->queryDepth;
63+
if ($this->queryDepth++ === 0) {
64+
$this->positions = new SplObjectStorage();
65+
}
6466
}
6567

6668
public function endQuery(): void
@@ -412,49 +414,10 @@ protected function isNot($node, $selector): bool
412414
return ! $this->has($node, $selector);
413415
}
414416

415-
/**
416-
* Get the relative position of a node in its sibling set.
417-
*/
418-
protected function nodePositionFromStart($node, $byType = false): int
419-
{
420-
$i = 1;
421-
$tag = $node->tagName;
422-
while (isset($node->previousSibling)) {
423-
$node = $node->previousSibling;
424-
if ($node->nodeType === XML_ELEMENT_NODE && ( ! $byType || $node->tagName === $tag)) {
425-
++$i;
426-
}
427-
}
428-
429-
return $i;
430-
}
431-
432-
/**
433-
* Get the relative position of a node in its sibling set.
434-
*
435-
* @param $node
436-
* @param bool $byType
437-
*
438-
* @return int
439-
*/
440-
protected function nodePositionFromEnd($node, $byType = false): int
441-
{
442-
$i = 1;
443-
$tag = $node->tagName;
444-
while (isset($node->nextSibling)) {
445-
$node = $node->nextSibling;
446-
if ($node->nodeType === XML_ELEMENT_NODE && ( ! $byType || $node->tagName === $tag)) {
447-
++$i;
448-
}
449-
}
450-
451-
return $i;
452-
}
453-
454417
/**
455418
* Record the position of every element child of $parent.
456419
*/
457-
protected function indexSiblings(DOMNode $parent): void
420+
protected function indexSiblings(DOMNode $parent, SplObjectStorage $positions): void
458421
{
459422
$elements = [];
460423
$typeCounts = [];
@@ -468,10 +431,7 @@ protected function indexSiblings(DOMNode $parent): void
468431

469432
$count = count($elements);
470433
foreach ($elements as $i => [$child, $typePos]) {
471-
$this->positions[$child] = [
472-
[$i + 1, $count - $i],
473-
[$typePos, $typeCounts[$child->tagName] - $typePos + 1],
474-
];
434+
$positions[$child] = [$i + 1, $count - $i, $typePos, $typeCounts[$child->tagName] - $typePos + 1];
475435
}
476436
}
477437

@@ -513,19 +473,12 @@ protected function isNthChild($node, $value, $reverse = false, $byType = false):
513473
}
514474

515475
// First we need to find the position of $node in other elements.
516-
if ($this->queryDepth > 0) {
517-
if ($this->positions === null) {
518-
$this->positions = new SplObjectStorage();
519-
}
520-
if (! $this->positions->offsetExists($node)) {
521-
$this->indexSiblings($parent);
522-
}
523-
$pos = $this->positions[$node][$byType ? 1 : 0][$reverse ? 1 : 0];
524-
} elseif ($reverse) {
525-
$pos = $this->nodePositionFromEnd($node, $byType);
526-
} else {
527-
$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);
528480
}
481+
$pos = $positions[$node][($byType ? 2 : 0) + ($reverse ? 1 : 0)];
529482

530483
// If group size is 0, we just check to see if this
531484
// 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/PseudoClassTest.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -658,10 +658,10 @@ protected function countingPseudoClass(): PseudoClass
658658
return new class extends PseudoClass {
659659
public $indexed = 0;
660660

661-
protected function indexSiblings(DOMNode $parent): void
661+
protected function indexSiblings(DOMNode $parent, SplObjectStorage $positions): void
662662
{
663663
++$this->indexed;
664-
parent::indexSiblings($parent);
664+
parent::indexSiblings($parent, $positions);
665665
}
666666
};
667667
}

0 commit comments

Comments
 (0)