简体   繁体   中英

Utilizing the GetHashCode() part of IEqualityComparer<T> for direct comparisons?

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

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.

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM