Skip to content

[System.Xml.Linq] Avoid quadratic traversal when loading nested XML - #136725

Open
asad24-dev wants to merge 1 commit into
dotnet:mainfrom
asad24-dev:investigate-runtime-136658
Open

asad24-dev wants to merge 1 commit into
dotnet:mainfrom
asad24-dev:investigate-runtime-136658

Conversation

@asad24-dev

Copy link
Copy Markdown
Contributor

Summary

When loading deeply nested XML, XContainer.AddNodeSkipNotify traverses the ancestor chain for each inserted node to prevent cycles.

The XML loader creates new, unattached nodes, so this traversal is unnecessary for these insertions. Repeating it at every nesting level introduces quadratic work.

This change adds a private loader-specific insertion method that skips the redundant ancestor traversal while preserving node validation, text conversion, and normal append behavior. The general-purpose insertion method and its cycle-prevention behavior remain unchanged.

Testing

  • System.Xml.Linq.Misc.Tests: 487 passed.
  • System.Xml.Linq.TreeManipulation.Tests: 15 passed.
  • Focused deep-nesting regression: passed.
  • Relevant library build: successful.

The regression test covers deeply nested XML using synchronous and asynchronous loading, default loading options, and metadata preservation.

Performance

Local measurements using the source-built runtime:

XML nesting depth Before After Speedup
10,000 215.1 ms 1.05 ms 205×
20,000 1,476.8 ms 1.71 ms 864×
40,000 5,811.7 ms 2.63 ms 2,208×

These measurements are workload- and environment-dependent. The change eliminates the unnecessary ancestor traversal responsible for the quadratic scaling.

Fixes #136658

@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 30, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-xml
See info in area-owners.md if you want to be subscribed.

This branch has not been deployed

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

Labels

area-System.Xml community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

XDocument.Parse / XDocument.Load take O(depth²) time: XContainer.AddNodeSkipNotify walks to the root for each added node

1 participant