Fast HashCode of a Complex Object Graph

不羁的心 提交于 2019-12-01 21:10:15

Given your comment, it sounds like you may be trying to rely on GetHashCode on its own to determine uniqueness. Don't do that. Hashes aren't meant to be unique - it's meant to be unlikely that two unequal objects will hash to the same value, but not impossible. If you're trying to check that a set of objects has no duplicates, you will have to use Equals as well.

Note that using XOR for a hashcode can make it more likely that you'll get hash collisions, depending on the individual hash values involved. In particular, it makes any two equal fields "cancel each other out". I generally use this form:

int hash = 17;
hash = hash * 31 + field1.GetHashCode();
hash = hash * 31 + field2.GetHashCode();
hash = hash * 31 + field3.GetHashCode();
hash = hash * 31 + field4.GetHashCode();
...
return hash;

... but even so, that's certainly not going to guarantee uniqueness. You should use GetHashCode() to rule out equality, and then use Equals to check the actual equality of any potentially equal values.

Now your question mentions speed - this sounds like the perfect place to use a profiler and some benchmark tests. Are you sure this is a bottleneck? If you have many different types all computing hash values, have you found out which of these is the biggest contributor to the problem?

Some optimisations will depend on exactly how you use the data. If you find that a lot of your time is spent recomputing hashes for values which you know haven't changed, you could cache the hash code... although this obviously becomes trickier when there are fields which themselves refer to complex objects. It's possible that you could cache "leaf node" hashes, particularly if those leaf nodes don't change often (but their usage could vary).

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