Description
The XML, HTML and HTML5 parsers copy every id attribute value into the document's id map as they build the tree (e.g. src/parser/xml.rs:838). Only element_by_id, CSS #id selectors and XPath id() read that map, so every parse pays for an index most callers never use. On parser_bench's documents with id attributes, that's roughly a tenth of parse time.
I'd like to propose building the index on demand instead:
element_by_idfirst checks ids registered withset_id, which DTD validation and callers use, as now.- Failing that, it uses an index of unprefixed
idattributes, built on the first lookup that needs it and held in aOnceLock, soDocumentstaysSend + Sync. - Every tree mutation goes through
node_mut, which discards the index, so the next lookup rebuilds it.
When several elements share an id, the last in document order still wins. Prefixed attributes such as p:id and xml:id still aren't indexed.
The behaviour change
Because the index would follow the tree, element_by_id would give different answers after the tree is edited:
After parsing <r><a id="x"/><b/></r> |
today | proposed |
|---|---|---|
remove_node(a), then element_by_id("x") |
Some(a), the detached node |
None |
set_attribute(b, "id", "y"), then element_by_id("y") |
None |
Some(b) |
create_element("c") with id="z", appended to r |
None |
Some(c) |
An element with an id attribute in a Document::new() tree |
None |
found |
These look like fixes to me, since today's map goes stale, but code relying on the old answers would notice. Are you happy with that?
Benchmarks
Change in time per iteration against main, from cargo bench --bench parser_bench and a second, noise-resistant harness, on an Apple M4:
parser_bench fixture |
change |
|---|---|
parse_small (10 ids) |
−14% to −19% |
parse_medium (100 ids) |
−8% to −14% |
parse_large (1,000 ids) |
−9% to −12% |
push_parser |
−8% to −10% |
roundtrip |
−11% to −13% |
validate_dtd |
−4% to −6% |
parse_html (50 ids) |
−1% to −10% (the two methods disagree) |
parse_html5, documents without ids, sax_parse |
no change |
The cost moves to the first lookup rather than disappearing: parsing parse_large's document and then calling element_by_id once comes out about even (−2%).
Implementation
It's ready on a branch, as one commit on main with tests for each row of the table above: https://github.com/dkam/xmloxide/tree/feature/tree-lazy-id-map
It passes fmt, tests on stable and 1.81, and docs locally. Clippy is clean apart from the lints already failing on main, which #74 fixes. I'll open it as a PR if the approach suits you, or adjust it if you'd prefer something different.
🤖 Generated with Claude Code
Activity
tree: build the element_by_id index on demand (fixes jonwiggins#76)