如何计算字符串列表的良好哈希码? [英] How do I calculate a good hash code for a list of strings?

查看:24
本文介绍了如何计算字符串列表的良好哈希码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:

  • 我有一个简短的字符串列表.
  • 字符串的数量并不总是相同,但几乎总是少数"的数量级
  • 在我们的数据库中将这些字符串存储在第二个规范化表中
  • 这些字符串一旦写入数据库就永远更改.

我们希望能够在查询中快速匹配这些字符串,而不会因执行大量连接而影响性能.

We wish to be able to match on these strings quickly in a query without the performance hit of doing lots of joins.

所以我想将所有这些字符串的哈希码存储在主表中并将其包含在我们的索引中,因此只有在哈希码匹配时数据库才会处理连接.

So I am thinking of storing a hash code of all these strings in the main table and including it in our index, so the joins are only processed by the database when the hash code matches.

那么我如何获得一个好的哈希码?我可以:

So how do I get a good hashcode? I could:

  • 对所有字符串的哈希码进行异或运算
  • 将每个字符串后的结果乘以异或(比如乘以 31)
  • 将所有字符串放在一起,然后得到哈希码
  • 其他方式

那么人们怎么看?

最后我只是连接字符串并计算用于连接的哈希码,因为它很简单并且工作得很好.

In the end I just concatenate the strings and compute the hashcode for the concatenation, as it is simple and worked well enough.

(如果您关心我们使用的是 .NET 和 SqlServer)

错误!错误!

引自 GetHashCode 的指南和规则作者:埃里克·利珀特

文档System.String.GetHashCode 注释特别是两个相同的字符串可以有不同的哈希码在不同版本的 CLR 中,以及事实上他们这样做.不要存储字符串在数据库中散列并期望它们永远一样,因为他们不会.

The documentation for System.String.GetHashCode notes specifically that two identical strings can have different hash codes in different versions of the CLR, and in fact they do. Don't store string hashes in databases and expect them to be the same forever, because they won't be.

因此不应为此使用 String.GetHashcode().

So String.GetHashcode() should not be used for this.

推荐答案

标准java实践,就是简单写

Standard java practise, is to simply write

final int prime = 31;
int result = 1;
for( String s : strings )
{
    result = result * prime + s.hashCode();
}
// result is the hashcode.

这篇关于如何计算字符串列表的良好哈希码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆