I've written a class deriving from IEqualityComparer<T>
which works great for the LINQ query I needed it for.
As I understand it, GetHashCode()
(fast) is called first, then Equals()
(slightly slower) if the hashcode is the same, for such operations.
However when using it for direct comparisons, manually, I'm using something like
return new MyIEqualityComparer().Equals(objA,objB);
Which forgoes the faster GetHashCode()
equality check. Is there a way of comparing objA
to objB
which doesn't automatically skip the faster GetHashCode()
check?
I guess I was hoping objA.Equals()
would have an overload that accepted an argument derived from IEqualityComparer<T>
.
It's not really clear what you're up to here, but you can always implement
IEquatable<T>
and delegate toMyIEqualityComparer
, thus using fasterGetHashCode()
:Computing a hash code and comparing the hash generally is slower than comparing for equality directly. It's additional work.
Hash codes are there to support the
O(1)
behavior of hash tables. They map an object to a number which is required for hash tables to work. Hash codes are not helpful for mere equality comparisons.Just use
Equals
.If you want to know how to best implement your idea (although it is not a good idea) I'd use a helper method:
(For educational purposes only.)
You might think that in case of a cached hash code this actually could be faster. But then
Equals
could make use of the cached hash code itself and short circuit the comparison.