Repository navigation
tree: build the element_by_id index on demand (fixes #76) - #80
Merged
Merged
Conversation
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #76. Thanks to dkam for the proposal, the measurements and the design (
OnceLockindex, invalidated innode_mut). This PR follows that design.What changes
parser/xml.rs), the HTML 4 parser (html/mod.rs) and the HTML5 foreign-element path (html5/tree_builder.rs) no longer callset_idfor everyidattribute during parsing.Document::element_by_idfirst checks IDs registered withset_id(DTD validation, callers). If none matches, it uses an index of unprefixedidattributes. 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 astd::sync::OnceLocksoDocumentstaysSend + Sync(there's a static assertion test).OnceLockhas been stable since 1.70, so MSRV 1.81 is fine.node_mutis 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 anAtomicBoolthroughget_mut(), which is a plain non-atomic load. CheckingOnceLock::get()/take()there instead cost about 3–5% on documents without ids, because that's an acquire load on everynode_mutcall.XPathid(), CSS#idand FFIxmloxide_element_by_idall go throughelement_by_id, so they pick this up automatically. I updated the FFI doc comment andinclude/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:
remove_node(a)whereahadid="x", thenelement_by_id("x")Some(a)(detached)Noneset_attribute(b, "id", "y")after parseNoneSome(b)idappended after parse / in aDocument::new()treeNoneparse_html5documents (HTML elements were never indexed)None. CSSselect(doc, "#x")also returned[]via the fast pathEntityRefchildren)NoneThese are unchanged:
set_idregistrations, including DTD-declared ID attributes with any name, take precedence and behave as before. They are still not invalidated on mutation, as before.xml:idand other prefixedidattributes are still not indexed.One pre-existing quirk this exposes more widely: CSS compound matching (
css/eval.rs) useselement_by_idand 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_benchtoo 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 matchparser_bench. Apple Silicon:parse_small(10 ids)parse_large(1,000 ids)parse_html(200 ids)parse_largewithout idsparse_large+ 1element_by_idparse_large+ 100 lookupselement_by_idon an indexed docSo 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.rscover:xml:id,p:id)remove_node,set_attribute/remove_attributewith the index already built, appended new elements (detached and then attached) andDocument::new()treesset_idprecedenceidID attribute alongside a plainidXPathid()before and after mutationSend + Syncstatic assertionChecks run:
cargo fmt --all --checkcargo clippy --all-targets --all-features -- -D warnings(stable and+1.100.0)cargo test --all-featurescargo doccargo +1.81 check --features cli,ffi, the MSRV configuration used by CI and the pre-commit hook.--all-featurescan't resolve on 1.81 because of the bench-only deps, same as on main.