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

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

问题描述

背景:

  • 在我有串短名单。
  • 串的数量并不总是相同的,但是一个少数
  • 的顺序的几乎总是
  • 在我们的数据库中会存储这些字符串在第二规范化表
  • 在这些字符串是永远更改一旦被写入到数据库中。
  • I have a short list of strings.
  • The number of strings is not always the same, but are nearly always of the order of a "handful"
  • In our database will store these strings in a 2nd normalised table
  • These strings are never changed once they are written to the database.

我们希望能够在这些字符串快速查询中的匹配没有做大量的连接的性能损失。

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

所以,我想存储所有这些字符串的哈希值code。在主表和包括在我们的索引,所以联接只能由数据库处理时散列code匹配。

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.

那么,如何才能获得一个好的哈希code?我可以:

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

  • 异或哈希$ C $全部串起来的CS
  • 异或与每个字符串(例如31)相乘后的结果
  • 猫全部串起来,然后让哈希code
  • 在一些其他的方式

那么人怎么看?

在最后,我只是在连接字符串和计算哈希值code为串联,因为它简单,已经足够好了。

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关心)

错误!错误!

从指导思想与GetHash code规则报价由埃里克利珀

该文档   System.String.GetHash code注   特别是两个相同的   字符串可以有不同的hash codeS   在不同版本的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.GetHash code()不应该被用于此目的。

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.

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

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