Skip to content

perf: compile each selector once in Element#matches - #349

Open
jonasporto wants to merge 3 commits into
WebReflection:mainfrom
jonasporto:perf/cache-compiled-matches
Open

jonasporto wants to merge 3 commits into
WebReflection:mainfrom
jonasporto:perf/cache-compiled-matches

Conversation

@jonasporto

@jonasporto jonasporto commented Oct 16, 2026 •

Copy link
Copy Markdown

Fixes #348

matches() passed the selector string to CSSselect.is(), which parses and compiles it on every call. This keeps the compiled function per selector string and document kind (xmlMode) in a Map capped at 1024 entries (the oldest is dropped first). Selectors with :scope still compile per call, since their context is the element.

Tests in test/html/document.js: a compiled selector follows later mutations, the same selector gives different results in an HTML and an XML document (fails if the cache ignores xmlMode), and more than 1024 selectors drop the oldest.

Benchmark

The script in #348 (96,048 calls), Node 22.17.0:

time
before (main, 3fcf145) ~108 ms
after ~20 ms

npm run build passes; coverage is the same as on main (100% statements, branches and lines).

Kept selectors and :has()

A kept compiled function must not keep css-select's result cache: with cacheResults (on by default), :has() remembers results per element inside the compiled function, so a kept selector answered from stale results after the DOM changed (a class added or removed, a child removed or put back, a second document). The second and third commits compile the kept selectors with cacheResults: false, and test positive and negative results across class, tree and reflected-attribute (slot) changes. The benchmark above is unchanged by it (5 runs each, Node 22.17.0: main 96–103 ms, this branch 18–19 ms). npm test passes on this branch merged with the current main (6e2ae0c), coverage 100%.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Element#matches() compiles the selector on every call

1 participant