Reputation:
In many situations, for simplicity's sake, I would have preferred to use a List or an HashSet in combination with LINQ instead of using a Dictionary. However, I usually sticked with Dictionary because I thought Dictionary would be more performant because of its hash table implementation.
For example:
When I do this in LINQ:
bool exists = hashset.Any(item => item.Key == someKey);
Do I lose significant performance compared to the following equivalent with a Dictionary?
bool exists = dictionary.ContainsKey(someKey); // an O(1) operation
Are the LINQ queries optimized in some way that would make them a justifiable choice against a Dictionary? Or is the above Any() a plain O(n) operation no matter on which type of collection it is executed?
Upvotes: 5
Views: 5417
Reputation: 51329
In your case you are eliminating the benefit of the hashset, because Any in that case is an extension method defined on IEnumerable. It is simply iterating over the hashset as if it were a List and invoking the == operator on each item. In fact, these two code samples are not even strictly equivalent- the LINQ statement uses the == operator, and the dictionary uses hashcode/equals equality. These are equivalent for value types and Strings, but not for all classes.
What you can do is this:
bool exists = hashset.Contains(item.Key);
That will use the Hashset's optimized lookup, and not require you to keep a dummy value as you would with Dictionary.
Upvotes: 9