perf(querying): use push/pop stacks in findAll and findOne

G4
8d ago
+38-22

findAll and findOne called unshift and shift on two stacks to walk the tree. This change keeps the current array and index in local variables. It uses push and pop only when the walk goes into a child array or comes back from it. The visit order and the results do not change.

dist build, ns/op:

BenchmarkBeforeAfterChange
selectAll("div") on a page with 2,083 elements169,44350,214-70.4%
selectAll("ul > li > a") on the same page172,03955,323-67.8%
4 attribute selectors on the same page790,034282,246-64.3%
selectOne with no match on 4,000 elements161,95666,716-58.8%
5,000 sibling elements431,378181,221-58.0%
1,500 nested elements399,33137,250-90.7%
3 queries on test/fixtures/sizzle.html83,28454,874-34.1%
400 separate root elements239,565198,499-17.1%

I measured no slowdown on 33 benchmarks. These include text-heavy documents, <template> content, XML mode, a tiny document, and selectOne with an early match. I used 12 interleaved rounds and a Mann-Whitney test (Apple M2 Max, Node 24.15.0).

Checks:

  • npm test passes.
  • Old and new outputs matched on 1,000,000 random cases in Node 24. Each case compares the results and errors of selectAll, selectOne, is, and compile. The cases use random documents, options, and adapters without prevElementSibling. The selectors are random, or they come from the 1,127 selector strings in test/.
  • Old and new outputs also matched on 100,000 cases each in Node 22.12, Bun 1.3.14, and Deno 2.9.1. I did not test Node 20.