Repository navigation
Closed as not planned
Labels
api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Collections
Milestone
Description
There are many times when there is a custom equality comparison being done but I need access to the original instance.
What I'd like:
var mergedItems = new HashSet<Item>();
foreach (var item in items)
{
mergedItems.GetOrAdd(item).RelatedInfo.Add(x);
}
public sealed class Item : IEquatable<Item>
{
public DateTime Date { get; }
public int Amount { get; }
public List<int> RelatedInfo { get; }
public bool Equals(Item other) => other != null && other.Date == Date && other.Amount == Amount;
public override bool Equals(object obj) => obj is Item item && Equals(item);
public override int GetHashCode() => // ...
}Today I'm forced to use a Dictionary which duplicates storage of the key for no reason.
A dictionary is also wasteful because it has to do two hash lookups, one for TryGetValue and one for Add:
var mergedItems = new Dictionary<Item, Item>();
foreach (var item in items)
{
if (!mergedItems.TryGetValue(item, out var otherItem))
mergedItems.Add(item, otherItem = item);
otherItem.RelatedInfo.Add(x);
}This is no better; it's a lot more to maintain, unnecessarily coupled to the definition of equality, it's still duplicate storage of the key, and it's still duplicating the number of hash lookups:
var mergedItems = new Dictionary<(DateTime, int), Item>();
foreach (var item in items)
{
if (!mergedItems.TryGetValue((item.Date, item.Amount), out var otherItem))
mergedItems.Add((item.Date, item.Amount), otherItem = item);
otherItem.RelatedInfo.Add(x);
}KeyedCollection is the worst of all because in addition to the dictionary, it keeps a list I'll never use.
Proposed API
namespace System.Collections.Generic;
public class HashSet<T>
{
+ /// <summary>
+ /// Searches the set for a given element and returns the equal element it finds, if any;
+ /// otherwise, adds the element to the set.
+ /// </summary>
+ /// <param name="item">The element to search for, or to add to the set.</param>
+ /// <returns>
+ /// The equal element that the search found, or the given element that was added to the set.
+ /// </returns>
+ public T GetOrAdd(T item);
}Reacted by Theodor Zoulias
Metadata
Metadata
Assignees
Labels
api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Collections
Activity
jnm2 commentedon May 9, 2017
Similar to https://github.com/dotnet/corefx/issues/11291 but not exactly a duplicate, since I don't want a generic parameter for the key or any other distinctions between keys and values.
svick commentedon May 10, 2017
You're not, if you're on .Net Core 2.0, you can use
HashSet<T>.TryGetValue()(https://github.com/dotnet/corefx/issues/15691), though it still requires two lookups.On one hand, the addition of
TryGetValueindicates that retrieving a value from aHashSetbased on a equal, but distinct value makes sense. On the other hand, it means addingGetOrAddis less important: it improves performance and convenience, but doesn't add new capabilities.jnm2 commentedon May 10, 2017
Sweet! That was the thread I couldn't find! So implementing GetOrAdd should be a piece of cake. @TylerBrinkley? :D
danmoseley commentedon May 10, 2017
@jnm2 there is a code size cost to adding new API to commonly instantiated generic types which means there is a higher bar for adding them. Consensus we achieved is here https://github.com/dotnet/corefx/issues/17275#issuecomment-291636863
Given this one could be achieved by an extension method, that might be the most palatable approach.,
jnm2 commentedon May 10, 2017
The extension method still has a downside, which is the duplicate hashtable lookup. In that sense, this is a fundamental operation. Too bad it can't be the other way around, other instance methods like Contains as extension methods implemented in terms of the fundamentals.
TylerBrinkley commentedon May 10, 2017
I think this one falls under the first criteria @terrajobst set for #17275 which is
While there is a performance hit of 2 lookups I don't think this method would be used all that much.
kellypleahy commentedon Jun 8, 2017
If we're going to do this, can we also have a
GetOrAddthat takes the factory function? This is something that seems also quite valuable? Also, can we put these onDictionary<TKey,TValue>(as extension methods) if they don't already exist too? Is there already a ticket forDictionary<TKey,TValue>?danmoseley commentedon Aug 19, 2018
@jnm2 can you clarify how this is not satisfied by #20073 ? I'm missing it.
jnm2 commentedon Aug 19, 2018
@danmosemsft #20073 doesn't provide any way to do
GetOrAddwithout a duplicate hash lookup, that I can see. It enables us to do this, but in the 'add' scenario, there is duplicate work being done in the calls toTryGetValueandAdd:@TylerBrinkley makes the point above that the performance hit of these duplicate lookups may not be important enough to add the instance method (requiring a bit more JIT time per generic instantiation).
There is indeed precedent for preferring extension methods at the cost of duplicate hash lookups:
https://github.com/dotnet/corefx/blob/b9ce86fbec92349c203a4c33805cffb8ca24c10f/src/System.Collections/src/System/Collections/Generic/CollectionExtensions.cs#L25-L39
However, see the opposite point being made by @jamesqo in the Dictionary.GetOrAdd issue: https://github.com/dotnet/corefx/issues/2877#issuecomment-319244808
danmoseley commentedon Aug 19, 2018
Ah yes i forgot we made an extension method. Given that decision it sounds like this issue can be closed?
The cost of growing commonly used generic types is the code size. Dictionary is one of the most sensitive, a small change can grow hello world size significantly.
jnm2 commentedon Aug 19, 2018
@danmosemsft #15059 is about Dictionary.GetOrAdd; this one is about HashSet.GetOrAdd. As far as I'm aware there is no extension method for GetOrAdd for either one.
kellypleahy commentedon Aug 19, 2018
@danmosemsft I'm a bit confused here. Does this really have such a big impact on code size? I think I'd be more worried personally about the performance impact of the second lookup than a tiny bit more code for each generic instantiation, but I guess that's just me (and I guess it really depends on whether people will actually use this instance method on hot code paths). Am I understanding properly that the impact would be an additional JITed function and an additional vtable entry (one each per generic instantiation, not per instance of objects), and the cost to perform the JIT on first use of said function?
danmoseley commentedon Aug 20, 2018
@jnm2 my bad, there's of course two asks here, one was "a custom equality comparison being done but I need access to the original instance." which seems now satisfied by
HashSet<T>.TryGetValue(as already observed above) and the other is to be able to "GetOrAdd", which as you say is not currently satisfied, although onDictionary<K,V>there isTryAddit doesn't return the value.As for the cost of adding to the type itself (in this case, necessary to avoid dual lookups) it is not the JIT time but the code duplication.
Dictionary<K,V>is instantiated many times in a typical app - once for reference types, then once for (I guess - not my area of expertise) each sized value type, and that can add up significantly. So several proposed additions to the type were either abandoned or moved to extension methods (which is unfortunate if like in this case it would be less efficient). I would expect this to be a lesser concern for HashSet since it's presumably instantiated for fewer types.@jkotas can you remind me of the kind of size increase you were quoting for a reasonably sized method addition to Dictionary?
jkotas commentedon Aug 20, 2018
I have been looking at the code size vs. benefit. I do not think I have said a universal number on how much it is ok to add.
danmoseley commentedon Aug 20, 2018
I meant, if I add a new 10-20 line method to Dictionary, as a rule of thumb how much does that increase the size of a typical app. I believe you gave a number but I cannot find it.
50 remaining items
CyrusNajmabadi commentedon Apr 18, 2024
As already stated: "it shouldn't be carte blanche for us to follow up with more mistakes."
Many API authors have intimate experience with this. Your past isn't perfect, and there are things you wish you hadn't done. But you learn from that and use that to inform future decisions. That means you pay more attention and are more careful. The experience with mistakes motivates you to go away from that space, not more toward it.
CyrusNajmabadi commentedon Apr 18, 2024
I'm not sure what can be done about that. However, it's part and parcel of every api decision made practically everywhere that their are constraints you have to work within. That's just life :) Maybe the constraints change in the future and you can revisit some decisions.
theodorzoulias commentedon Apr 18, 2024
And why exactly was the
TryGetValuea mistake? It is certainly benefiting the developers who are searching for it, finding it, and using it. Do you know of anyone who, on the basis of Eirik's theoretical argument, has been harmed by it? This question is relevant to our discussion about theGetOrAdd, because if theTryGetValuehasn't harmed anyone, neither theGetOrAddwill. These two APIs are interconnected. Currently the only way to implement theGetOrAdd(inefficiently though), is to search for the element with theTryGetValue, and if it's not found thenAddit to the set.CyrusNajmabadi commentedon Apr 18, 2024
I'd consider myself harmed, due to the confusion such an API causes, and the bizarre sort of dual view where there can be different equality concepts.
--
Yup, giving this more thought, i really think that API was def a mistake. Even the use case is much better served by using a Dictionary. It's clear, reasonable, and already about what Dictionarys are intended for (mapping from one domain to another). That the key and value domains overlap in terms of their types, that they have different equality concepts (IEquatable vs Identity) means they should be separated out and not collapsed into a single entity to me.
CyrusNajmabadi commentedon Apr 18, 2024
Note: i'm not opposed to a back-door for perf. But i would keep well outside of the mainline api as this just feels very broken.
theodorzoulias commentedon Apr 18, 2024
@CyrusNajmabadi well, you can certainly substitute hashsets with dictionaries in most everyday scenarios. If you need a
HashSet<T>for lookups, and not for its specialized APIs (IntersectWith,IsSubsetOfetc), then just use aDictionary<T, object>, ignore theTValueand call it a day. Bigger memory footprint, but one less collection to have in mind. Not only you will be less harmed by theTryGetValue, but also by theHashSet<T>collection as a whole.(I am half-joking here, because I think that you are half-joking as well.)
CyrusNajmabadi commentedon Apr 18, 2024
I'm not joking at all. I think sets should be used only when everything is treated uniformly in the domain of hte equality contract picked for the collection. If you need differing equality contracts, use a dictionary, it properly models that these are distinct spaces.
As i mentioned already, i would not be opposed to a back-door api here if absolute perf is needed. But i would not make it part of the core surface contract of HashSet.
If i have such a set with such strange equality concepts, i would be very wary about using any of those apis. I would def want to spell out precisely what semantics i was expecting, and would likely prefer a dictionary here to keep things clear.
theodorzoulias commentedon Apr 18, 2024
@CyrusNajmabadi the concept of embedding a key inside the items stored in a collection is as old as the
KeyedCollection<TKey,TItem>. Which was released with the .NET Framework 2.0, so it's 18+ years old. Some people, myself included, like the concept but not the implementation, so we are re-implementing it using the most lightweight collection suitable for the task, which is theHashSet<T>. To do this we need theTryGetValue, and since your are not joking about being harmed by the existence of this API, I feel obliged to apologize on behalf of all the developers who have used it. Also I appreciate that you support the quest forCollectionsMarshalsupport for theHashSet<T>collection. There are many obstacles to overcome before this support is materialized, with the first being that the relevant API proposal #82840 is currently locked.CyrusNajmabadi commentedon Apr 18, 2024
That's sometimes how things just fall out. Trust me, there are probably around 500 apis i'd love that would make my life materially better. But i'm not going to be able to adequately justify those apis happening in the core runtime apis themselves. That's life.
Yes. For context, i've worked on .Net since before it was 1.0. I'm very familiar with its history (and its massive warts). I don't look at things like that as any sort of good argument for continuing with such decisions in the future. As mentioned before, i want us to look to the past to see what we can learn from it, esp. about what not to do.
Sure. But, like with all api requests, just because you have a need/desire here, is only part of the equation. Every API request ever is driven by people trying to solve problems, where they've decided to use some API and have found it lacking. The goal of the runtime is to get in that feedback, and weigh all the factors involved, to make the best choices for the needs of the ecosystem as a whole. And, a lot of the time, that means that people wanting those api changes will not get what they want. In that case you have to decide how impactful that is to you. If it's something you can live with, great. If not, that sometimes means you have to build your own solution.
As someone who has built easily hundreds of APIs (some of which did end up rolling into the BCL, but most of which did not), i'm very familiar with this :)
eiriktsarpalis commentedon Apr 18, 2024
@kellypleahy fully deserializing an object only to later discard it on the basis of duplication sounds inefficient to me. The cost of double lookup should be multiple orders of magnitude smaller compared to deserialization so a
GetOrAddmethod wouldn't move the needle much.You keep repeating that my argument is theoretical, but bugs related to inappropriate use of equality are very real and very common. In concrete terms, this pattern encourages definitions of equality that only make sense when scoped to one particular hash table. This creates problems because, generally speaking, we encourage that types have universal equality semantics (e.g. via the CA2231 and CA1067 analyzers). Assuming that equality uses projection semantics (e.g. like the
Itemclass cited by the OP) then the outcome of the==operator is bound to be misused in other contexts. Things become even trickier if the type additional needs to implement comparison semantics, because it will need to be kept compatible with equality.If there's a broader takeaway to be made here, equality is hard and you should avoid implementing it manually unless there is a very compelling reason to do it. The language(s) and framework provide tools that let you (mostly) delegate that responsibility: I personally use tuples and records whenever I have a need to represent structural equality for complex data:
The BCL is an aggregate of over 20 years of shifting programming paradigms, patterns and, yes, in some cases mistakes. Some APIs have stood the test of time, others not so much. It does not follow that we should be doubling down on a particular pattern just because an instance of it got shipped at some point in time. Neither does not aggressively removing/deprecating APIs deemed obsolete by one member of the BCL team betray some sort of hypocricy or double standard as you're suggesting: it's simply not worth doing from a cost-benefit analysis for most cases.
theodorzoulias commentedon Apr 18, 2024
@eiriktsarpalis how many bugs do you believe have been caused by the introduction of the
TryGetValueAPI, that resulted in defective lookup functionality in production code, since the August of 2017 when the API was first released with .NET Core 2.0? Furthermore, how many bugs do you believe will be prevented in the future by blocking theGetOrAddAPI proposal here? I can only guess the answer for the first question, but I am pretty sure about the second. Exactly zero bugs will be prevented, because no one who is thinking to switch from aDictionary<K,V>to aHashSet<T>for whatever reason, will see the lack of theGetOrAddas a show-stopper. The functionality of theGetOrAddcan be trivially implemented with the combinationTryGetValue+Add, which is good enough for every imaginable scenario. It's just not perfectly efficient. So all this discussion here about equality definitions etc seems to me that is in vain.I should mention that not only the
HashSet<T>collection, but also theImmutableHashSet<T>,ImmutableSortedSet<T>,SortedSet<T>andFrozenSet<T>are equipped withTryGetValuemethods withT equalValue, out T actualValueparameters. I didn't know that, I just learned it by reading the #20073 where theTryGetValuewas approved (on Feb 7, 2017), and then doing a search in the docs. Which makes the whole fight against multiple equality definitions even more futile IMHO. Isn't it obvious that the ship has sailed on this?eiriktsarpalis commentedon Apr 18, 2024
I don't think anybody in this thread expressed interest in preventing users from using HashSet to their heart's content. The concern that actually has been expressed is that we don't introduce new methods to popular generic types willy-nilly, particularly ones that are of questionable utility and can be worked around trivially as you are pointing out.
theodorzoulias commentedon Apr 18, 2024
Eirik I interpreted this previous comment:
...as a desire to discourage developers from making creative use of the
HashSet<T>collection, when a semantically straightforwardDictionary<K,V>-based solution exists. Βeing opposed to theTryGetValueAPI, and hypothetically going back in time and preventing it from being approved, would certainly be a strong discouragement. Without it the opportunities for using creatively theHashSet<T>would be greatly diminished.