perf(pseudos): index sibling positions for :nth-*

TH
1d ago
+189-20

:nth-child, :nth-last-child, :nth-of-type and :nth-last-of-type count earlier siblings by rescanning the sibling list for every element, so selecting across a list of n siblings is O(n²). This is noticeable through cheerio on long lists and tables ($("li:nth-child(2n)") on 16k items takes ~0.75s).

This records each sibling's position the first time the list is scanned and resumes the scan from where it stopped, so a list is walked once per compiled query. It's gated on cacheResults like cacheParentResults, with the existing loop kept as the uncached path and as the fallback for adapters that hand out fresh node objects or use primitives as nodes. :nth-child(An+B of S) stays uncached, since S can depend on a context that :has changes between calls (e.g. :scope). The scan stops at the element being checked, so a one-off is() on an early child does no extra work.

selectAll on a <ul> where every third child is a <p> (Node 24, M4 Pro):

siblingsselectorbeforeafter
100:nth-child(2n)0.036 ms0.013 ms
1,000:nth-child(2n)2.9 ms0.13 ms
1,000li:nth-of-type(odd)2.7 ms0.13 ms
16,000:nth-child(2n)755 ms2.2 ms
16,000li:nth-of-type(odd)710 ms2.1 ms
16,000li:nth-last-child(3)236 ms1.9 ms

Lists of ~10 siblings and selectors that never reach the :nth-* check (e.g. tr:nth-child(2) with no tr) are unchanged within noise.

I also compared results against the current version on 400 random documents (mixed tags, text and comments) × 148 selectors covering all four pseudos, of S, and use inside :has/:not/:is/~, plus a compiled query reused across two documents: all identical. The added tests check the cached path against cacheResults: false with elements visited out of order, count isTag calls to catch a return to per-element rescans, and cover of S under :has with :scope.

Summary by CodeRabbit

  • Performance
    • Repeated positional selector queries can be faster when caching is enabled, WeakMap is available, and no of selector is specified. Other cases continue to use sibling scans.
  • Tests
    • Added checks comparing cached and uncached results after reordered lookups, measuring sibling-scan efficiency across large sibling lists, verifying sibling-array reuse across parents, and confirming that of selector positions remain distinct across contexts.