Skip to content

Fix ListDictionaryInternal.Count to not be O(n)#123899

Merged
stephentoub merged 1 commit intodotnet:mainfrom
stephentoub:exceptiondatakeyscount
Feb 2, 2026
Merged

Fix ListDictionaryInternal.Count to not be O(n)#123899
stephentoub merged 1 commit intodotnet:mainfrom
stephentoub:exceptiondatakeyscount

Conversation

@stephentoub
Copy link
Member

Rarely used but also unnecessary.

Rarely used but also unnecessary.
@dotnet-policy-service
Copy link
Contributor

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

Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes the Count property of the nested NodeKeyValueCollection class within ListDictionaryInternal by eliminating an unnecessary O(n) traversal. The ListDictionaryInternal class already maintains a count field that is incremented on Add operations and decremented on Remove operations, accessible through the public Count property (line 83). The nested collection's ICollection.Count implementation was unnecessarily iterating through all nodes to compute the count, when it could simply delegate to the parent list's already-tracked count.

Changes:

  • Simplified NodeKeyValueCollection.ICollection.Count from an O(n) implementation that traverses the linked list to an O(1) property that returns list.Count

@stephentoub stephentoub enabled auto-merge (squash) February 2, 2026 18:30
@stephentoub stephentoub merged commit 6f437d9 into dotnet:main Feb 2, 2026
150 of 154 checks passed
lewing pushed a commit to lewing/runtime that referenced this pull request Feb 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants