Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

.net - How do I calculate a good hash code for a list of strings?

Background:

  • 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.

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:

  • Xor the hash codes of all the string together
  • Xor with multiply the result after each string (say by 31)
  • Cat all the string together then get the hashcode
  • Some other way

So what do people think?


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

(If you care we are using .NET and SqlServer)


Bug!, Bug!

Quoting from Guidelines and rules for GetHashCode by Eric Lippert

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...