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

最后都变了- 提交于 2019-12-06 07:53:35

问题


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


来源:https://stackoverflow.com/questions/37724752/utilizing-the-gethashcode-part-of-iequalitycomparert-for-direct-comparisons

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!