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

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

问题描述:

我已经编写了一个从IEqualityComparer<T>派生的类,该类非常适合我需要的LINQ查询.

I've written a class deriving from IEqualityComparer<T> which works great for the LINQ query I needed it for.

据我了解,对于此类操作,首先调用GetHashCode()(快速),然后调用Equals()(稍慢)(如果哈希码相同).

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

放弃了更快的GetHashCode()相等性检查.有没有一种方法可以将objAobjB进行比较,而不会自动跳过更快的GetHashCode()检查?

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?

我想我希望objA.Equals()可以接受从IEqualityComparer<T>派生的参数的重载.

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.

哈希码可以支持哈希表的O(1)行为.它们将对象映射到哈希表起作用所需的数字.哈希码对仅进行相等比较没有帮助.

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.

只需使用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);
}

(仅用于教育目的.)

您可能会认为,在缓存哈希码的情况下,这实际上可能会更快.但是随后Equals可以利用缓存的哈希码本身并缩短比较的时间.

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.