Skip to content

tree: build the element_by_id index on demand (fixes #76) - #80

Merged
jonwiggins merged 2 commits into
mainfrom
perf/lazy-id-index
Nov 20, 2026
Merged

jonwiggins merged 2 commits into
mainfrom
perf/lazy-id-index

Conversation

@jonwiggins

Copy link
Copy Markdown
Owner

Fixes #76. Thanks to dkam for the proposal, the measurements and the design (OnceLock index, invalidated in node_mut). This PR follows that design.

What changes

  • The XML parser (parser/xml.rs), the HTML 4 parser (html/mod.rs) and the HTML5 foreign-element path (html5/tree_builder.rs) no longer call set_id for every id attribute during parsing.
  • Document::element_by_id first checks IDs registered with set_id (DTD validation, callers). If none matches, it uses an index of unprefixed id attributes. The index is built from the tree (document order, so the last duplicate still wins) on the first lookup that needs it, and it is held in a std::sync::OnceLock so Document stays Send + Sync (there's a static assertion test). OnceLock has been stable since 1.70, so MSRV 1.81 is fine.
  • node_mut is the only way tree nodes get mutated (all public mutators and the parsers go through it), so it discards the index. To keep the parsers' hot path cheap, it checks an AtomicBool through get_mut(), which is a plain non-atomic load. Checking OnceLock::get() / take() there instead cost about 3–5% on documents without ids, because that's an acquire load on every node_mut call.
  • XPath id(), CSS #id and FFI xmloxide_element_by_id all go through element_by_id, so they pick this up automatically. I updated the FFI doc comment and include/xmloxide.h, which said DTD validation was required. The wasm and Python bindings don't expose ID lookup.

No public API signatures change.

Behaviour changes (please review)

Lookups now follow the current tree rather than a map built at parse time:

Scenario before after
remove_node(a) where a had id="x", then element_by_id("x") Some(a) (detached) None
set_attribute(b, "id", "y") after parse None Some(b)
new element with id appended after parse / in a Document::new() tree None found
parse_html5 documents (HTML elements were never indexed) None. CSS select(doc, "#x") also returned [] via the fast path found
elements inside expanded entity content (EntityRef children) None found

These are unchanged:

  • set_id registrations, including DTD-declared ID attributes with any name, take precedence and behave as before. They are still not invalidated on mutation, as before.
  • xml:id and other prefixed id attributes are still not indexed.
  • Duplicates still resolve to the last element in document order.

One pre-existing quirk this exposes more widely: CSS compound matching (css/eval.rs) uses element_by_id and so matches only the last of duplicate ids. HTML5 documents now hit that path too, where before they fell back to an attribute scan. I left CSS alone; it could be a follow-up.

Benchmarks

The machine was under load from other jobs during the criterion run, which made cargo bench --bench parser_bench too noisy to trust: unrelated benches swung ±30–150%. I used an A/B harness instead. It builds main and this branch as separate binaries (release, codegen-units = 1), runs them interleaved three times, and takes the median of 41 samples each. The fixtures match parser_bench. Apple Silicon:

Workload main this PR change
parse_small (10 ids) 5.15 µs 4.35–4.45 µs −14 to −16%
parse_large (1,000 ids) 1.031 ms 0.906–0.917 ms −11 to −12%
parse_html (200 ids) 143.4 µs 120.3 µs −16%
parse_large without ids 0.905 ms 0.908–0.917 ms ~+0.5% (noise)
parse_large + 1 element_by_id 1.031 ms 1.021–1.030 ms ≈ 0
parse_large + 100 lookups 1.035 ms 1.026–1.035 ms ≈ 0
element_by_id on an indexed doc 17 ns 17 ns 0

So parsing gets 11–16% faster on documents with ids. A caller who does look up IDs breaks even, because the cost moves to the first lookup instead of disappearing.

Testing

New tests in src/tree/mod.rs cover:

  • lookup after parse
  • the duplicate rule
  • prefixed ids ignored (xml:id, p:id)
  • remove_node, set_attribute / remove_attribute with the index already built, appended new elements (detached and then attached) and Document::new() trees
  • set_id precedence
  • DTD validation with a non-id ID attribute alongside a plain id
  • XPath id() before and after mutation
  • HTML 4 and HTML5 parsers
  • a Send + Sync static assertion

Checks run:

  • cargo fmt --all --check
  • cargo clippy --all-targets --all-features -- -D warnings (stable and +1.100.0)
  • cargo test --all-features
  • cargo doc
  • cargo +1.81 check --features cli,ffi, the MSRV configuration used by CI and the pre-commit hook. --all-features can't resolve on 1.81 because of the bench-only deps, same as on main.

The XML, HTML 4 and HTML5 (foreign-content) parsers copied every `id`
attribute into the document's ID map while building the tree, costing
roughly a tenth of parse time on id-heavy documents even though only
element_by_id, XPath id() and CSS #id ever read it.

element_by_id now checks IDs registered with set_id (DTD validation,
callers) first, then falls back to an index of unprefixed `id`
attributes built from the tree on first use and held in a OnceLock, so
Document stays Send + Sync. node_mut, the single tree-mutation entry
point, discards the index; it tests a flag via AtomicBool::get_mut so
the parsers' hot path pays only a plain load.

Because the index follows the current tree, lookups no longer return
removed elements, find elements given an id after parsing, and now find
elements from parse_html5 and inside expanded entity content.
@jonwiggins
jonwiggins merged commit c860c28 into main Nov 20, 2026
6 checks passed
@jonwiggins
jonwiggins deleted the perf/lazy-id-index branch November 20, 2026 22:11
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.

Build the element_by_id index on demand instead of during every parse

1 participant