You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We added GetAlternateLookup() to many collection types, including Dictionary<TKey, TValue> and HashSet<T>. We should add it to SortedSet<T> as well, for symmetry. In my case, I often use SortedSet<string> over HashSet<T> because I'm persisting data to disk and I'd like to have a stable order to make diffs less jarring.
A side question: is there any interface support for the alternate lookups? For example, can I use the Dictionary<TKey, TValue>.AlternateLookup<TAlternateKey> as a IDictionary<TAlternateKey, TValue>? The api surface on alternate lookups doesn't naturally provide Keys in alternate key or kvp support, but they can be easily filled. For ISet<T>, the api surface on alternate lookup is significantly smaller.
I will repeat the feedback I put in the original issue. Do allocation-heavy tree-based sets with $\mathcal O(\log n)$ lookup warrant the performance improvement of span-based lookups? If we think that it's necessary, don't we also need an IAlternateComparer<T, TAlternate> complement to IComparer<T> that mirrors the IAlternateEqualityComparer<T, TAlternate> interface? Should we extend this to immutable sorted collections?
If we think that it's necessary, don't we also need an IAlternateComparer<T, TAlternate> complement to IComparer that mirrors the IAlternateEqualityComparer<T, TAlternate> interface?
I suspect this would be difficult to sign off on without a PoC created ahead of time. @terrajobst should we mark it needs-work or do we want to review the proposal in principle first?
This proposal was drafted with the help of an AI agent. Please review for accuracy and remove this notice once you're satisfied with the content.
Background and motivation
Dictionary<TKey,TValue> and HashSet<T> support allocation-free lookups via AlternateLookup and IAlternateEqualityComparer<TAlternate, T>. However, comparison-based sorted collections (SortedSet<T>, SortedDictionary<TKey,TValue>, SortedList<TKey,TValue>) lack this because they use IComparer<T>, not IEqualityComparer<T>.
Today, looking up a ReadOnlySpan<char> key in a SortedDictionary<string, TValue> requires allocating a string:
A new IAlternateComparer<TAlternate, T> interface (analogous to IAlternateEqualityComparer) enables the same allocation-free pattern for sorted collections.
IAlternateComparer has Compare + Create (no GetHashCode): Comparison-based collections don't need hash codes, unlike IAlternateEqualityComparer which has Equals + GetHashCode + Create.
SortedList.AlternateLookup includes IndexOfKey: SortedList uniquely exposes index-based access; the alternate lookup preserves this capability.
SortedSet.AlternateLookup.Remove does a double traversal: FindNode with the alternate comparer, then DoRemove with the actual item. This is correct because DoRemove requires the actual T for tree rebalancing. The cost is O(log n) + O(log n) = O(log n).
Alternative Designs
Reuse IAlternateEqualityComparer: Not possible — sorted collections use IComparer<T>, not IEqualityComparer<T>. A comparison requires ordering information (Compare returning int), not just equality (Equals returning bool).
Add Compare to IAlternateEqualityComparer: Would pollute the equality-only interface with comparison concerns and break existing implementers.
Risks
No binary breaking changes: Only additive APIs.
No source breaking changes: New methods are on new nested types; partial keyword added to existing classes is source-compatible.
GenFacades incompatibility: The allows ref struct syntax is not supported by the GenFacades tool used in partial facade assemblies. The new *.AlternateLookup.cs files are excluded from GenFacades processing via <ExcludeFromGenFacades>true</ExcludeFromGenFacades> metadata.
Open Questions
Should immutable sorted collections (ImmutableSortedSet, ImmutableSortedDictionary) also get AlternateLookup? (Suggest as future work.)
Should Array.BinarySearch and List<T>.BinarySearch accept IAlternateComparer? (Suggest as future work.)
Activity
dotnet-policy-service commentedon Oct 8, 2024
Tagging subscribers to this area: @dotnet/area-system-collections
See info in area-owners.md if you want to be subscribed.
huoyaoyuan commentedon Oct 8, 2024
A side question: is there any interface support for the alternate lookups? For example, can I use the
Dictionary<TKey, TValue>.AlternateLookup<TAlternateKey>as aIDictionary<TAlternateKey, TValue>? The api surface on alternate lookups doesn't naturally provideKeysin alternate key or kvp support, but they can be easily filled. ForISet<T>, the api surface on alternate lookup is significantly smaller.PaulusParssinen commentedon Oct 8, 2024
I attempted API proposal for this at #101694 but I folded pretty quick.
eiriktsarpalis commentedon Oct 8, 2024
I will repeat the feedback I put in the original issue. Do allocation-heavy tree-based sets with$\mathcal O(\log n)$ lookup warrant the performance improvement of span-based lookups? If we think that it's necessary, don't we also need an
IAlternateComparer<T, TAlternate>complement toIComparer<T>that mirrors theIAlternateEqualityComparer<T, TAlternate>interface? Should we extend this to immutable sorted collections?stephentoub commentedon Oct 8, 2024
For what purpose?
eiriktsarpalis commentedon Oct 8, 2024
Don't we need a mechanism that determines whether the proposed
GetAlternateLookup<TAlternate>();call succeeds for a particular set?stephentoub commentedon Oct 8, 2024
If we add the Get, we should add the TryGet, too.
eiriktsarpalis commentedon Oct 8, 2024
I suspect this would be difficult to sign off on without a PoC created ahead of time. @terrajobst should we mark it needs-work or do we want to review the proposal in principle first?
terrajobst commentedon Oct 15, 2024
If we do the work, we probably want to all comparison-based data structures, such as:
SortedSet<T>OrderedDictionary<TKey, TValue>SortedDictionary<TKey, TValue>SortedList<TKey, TValue>eiriktsarpalis commentedon Oct 15, 2024
As well as all binary search methods that accept
IComparer<T>.bartonjs commentedon Oct 15, 2024
Video
eiriktsarpalis commentedon Feb 26, 2026
Note
This proposal was drafted with the help of an AI agent. Please review for accuracy and remove this notice once you're satisfied with the content.
Background and motivation
Dictionary<TKey,TValue>andHashSet<T>support allocation-free lookups viaAlternateLookupandIAlternateEqualityComparer<TAlternate, T>. However, comparison-based sorted collections (SortedSet<T>,SortedDictionary<TKey,TValue>,SortedList<TKey,TValue>) lack this because they useIComparer<T>, notIEqualityComparer<T>.Today, looking up a
ReadOnlySpan<char>key in aSortedDictionary<string, TValue>requires allocating astring:A new
IAlternateComparer<TAlternate, T>interface (analogous toIAlternateEqualityComparer) enables the same allocation-free pattern for sorted collections.API Proposal
StringComparersubclasses (CultureAwareComparer,OrdinalComparer,OrdinalCaseSensitiveComparer,OrdinalIgnoreCaseComparer) implementIAlternateComparer<ReadOnlySpan<char>, string?>, matching the existingIAlternateEqualityComparerpattern.API Usage
Design Decisions
IAlternateComparerhasCompare+Create(noGetHashCode): Comparison-based collections don't need hash codes, unlikeIAlternateEqualityComparerwhich hasEquals+GetHashCode+Create.SortedList.AlternateLookupincludesIndexOfKey:SortedListuniquely exposes index-based access; the alternate lookup preserves this capability.SortedSet.AlternateLookup.Removedoes a double traversal: FindNode with the alternate comparer, thenDoRemovewith the actual item. This is correct becauseDoRemoverequires the actualTfor tree rebalancing. The cost is O(log n) + O(log n) = O(log n).Alternative Designs
IAlternateEqualityComparer: Not possible — sorted collections useIComparer<T>, notIEqualityComparer<T>. A comparison requires ordering information (Comparereturning int), not just equality (Equalsreturning bool).ComparetoIAlternateEqualityComparer: Would pollute the equality-only interface with comparison concerns and break existing implementers.Risks
partialkeyword added to existing classes is source-compatible.allows ref structsyntax is not supported by the GenFacades tool used in partial facade assemblies. The new*.AlternateLookup.csfiles are excluded from GenFacades processing via<ExcludeFromGenFacades>true</ExcludeFromGenFacades>metadata.Open Questions
ImmutableSortedSet,ImmutableSortedDictionary) also getAlternateLookup? (Suggest as future work.)Array.BinarySearchandList<T>.BinarySearchacceptIAlternateComparer? (Suggest as future work.)Related Issues
api-needs-workfeedback)SortedSet<T>andSortedDictionary<T>#101694 — Prior closed proposal by a different authorPrototype
Branch:
api-proposal/alternate-comparerCommit:
6f0332127b9Add an api-proposal Copilot skill (#124808)