Utilizing the GetHashCode() part of IEqualityCompa

2020-07-24 03:58发布

问题:

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>.

回答1:

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:

static bool ExperimentalEquals<T>(T a, T b, IEqualityComparer<T> c) {
 if (c.GetHashCode(a) != c.GetHashCode(b)) return false;
 return c.Equals(a, b);
}

(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.



回答2:

It's not really clear what you're up to here, but you can always implement IEquatable<T> and delegate to MyIEqualityComparer, thus using faster GetHashCode():

class My : IEquatable<My>
{
    public bool Equals(My other)
    {
        return new MyIEqualityComparer().Equals(this, other);
    }
}