通过Equals或HashCode进行比较。哪个更快? [英] Comparison via Equals or HashCode. which is faster?
问题描述
我必须将一个对象与同一类的原始属性进行比较。
的意思是,我必须将它们进行比较:
I have to compare a object with the raw properties of the same class. Meaning, i have to compare those:
struct Identifier
{
string name;
string email;
}
,带有两个字符串名称和电子邮件。
我知道我可以为名称和电子邮件创建一个新的Identifier实例,并将其传递给equals()。我的应用程序必须非常快速且节省资源。
with the two strings name and email. I know i could just create a new Identifier instance for name and email and pass that into equals(). My application has to be very fast and resource-saving.
我知道通过哈希码进行比较不是一种好方法,因为如有碰撞。但是碰撞对我来说还可以,我只需要它快即可。
I know that comparison via hashcode isn't a good way, because as explained here there are collisions. But collisions are okay for me, i just need it to be fast.
所以,
1)是通过GetHashCode进行比较(检查两个对象的哈希码是否相同)比Equals()更快?
1) is comparison via GetHashCode (check if the hashcode of both objects are the same) faster than Equals()?
2)我是否应该创建两个标识符的新实例?进行比较的值,制作一个直接采用这些值的新方法?例如,
2) Should i instead creating a new instance of Identifier of the two values for the comparison, make a new method which takes the values directly? e.g.
struct Identifier {
string name;
string email;
bool Equals(string name, string email) {
// todo comparison via hashcode or equals
}
}
我会使用Equals()和GetHashCode ()方法由resharper生成。
推荐答案
如果将哈希码保存在<$上,则比较哈希码可能会更快。 c $ c>标识符实例(请参见下文)。但是,与进行相等性比较不是同一回事。
Comparing hash codes could be faster if you save them on the Identifier
instance (see below). However, it is not the same thing as comparing for equality.
比较哈希码可以检查两个项是否确实等于 其他:当您获得不同的哈希码时,您会知道这一点。
Comparing hash codes lets you check if two items are definitely not equal to each other: you know this when you get different hash codes.
但是,当哈希码相等时,您就不能对等式做出明确的声明:项目可以相等或彼此不相等。这就是为什么基于散列的容器必须始终遵循直接或间接的散列代码比较,并进行相等性比较。
When hash codes are equal, however, you cannot make a definitive statement about the equality: the items could be equal or not equal to each other. That is why hash-based containers must always follow hash code comparison, direct or indirect, with a comparison for equality.
尝试像这样实现比较:
struct Identifier {
string name;
string email;
int nameHash;
int emailHash;
public Identifier(string name, string email) {
this.name = name;
nameHash = name.GetHashCode();
this.email = email;
emailHash = email.GetHashCode();
}
bool Equals(string name, string email) {
return name.GetHashCode() == nameHash
&& email.GetHashCode() == emailHash
&& name.equals(this.name)
&& email.equals(this.email);
}
}
与预先计算的哈希码相比会短路实际的相等性比较,因此当大多数比较最终返回 false
时,您可以节省一些CPU周期。
Comparing to pre-computed hash code would short-circuit the actual equality comparison, so you could save some CPU cycles when most of the comparisons end up returning false
.
这篇关于通过Equals或HashCode进行比较。哪个更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!