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.


你不清楚你在这里做什么,但你总是可以实现IEquatable<T>并委托给MyIEqualityComparer ,从而使用更快的GetHashCode()

class My : IEquatable<My>
{
    public bool Equals(My other)
    {
        return new MyIEqualityComparer().Equals(this, other);
    }
}
链接地址: http://www.djcxy.com/p/6770.html

上一篇: 当Equals方法被覆盖时为什么重写GetHashCode很重要?

下一篇: 利用IEqualityComparer <T>的GetHashCode()部分进行直接比较?