简体   繁体   English

利用IEqualityComparer的GetHashCode()部分 <T> 直接比较?

[英]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. 我编写了一个派生自IEqualityComparer<T> ,它非常适合我需要它的LINQ查询。

As I understand it, GetHashCode() (fast) is called first, then Equals() (slightly slower) if the hashcode is the same, for such operations. 据我了解,首先调用GetHashCode() (fast),然后调用Equals() (稍慢),如果hashcode相同,则进行此类操作。

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. 放弃了更快的GetHashCode()相等性检查。 Is there a way of comparing objA to objB which doesn't automatically skip the faster GetHashCode() check? 有没有办法比较objAobjB ,它不会自动跳过更快的GetHashCode()检查?

I guess I was hoping objA.Equals() would have an overload that accepted an argument derived from IEqualityComparer<T> . 我想我希望objA.Equals()有一个重载接受从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. 哈希代码用于支持哈希表的O(1)行为。 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 . 只需使用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. 但是Equals可以利用缓存的哈希代码本身并将比较短路。

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() : 目前还不清楚你在做什么,但你总是可以实现IEquatable<T>并委托给MyIEqualityComparer ,因此使用更快的GetHashCode()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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