Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A fast hash function for string in C#

I want to hash a string of length up-to 30. What will be the best idea to do that if time is my concern. The function will be called over 100 million times. currently I am using the following code,

static UInt64 CalculateHash(string read, bool lowTolerance) {     UInt64 hashedValue = 0;     int i = 0;     while (i < read.Length)     {         hashedValue += read.ElementAt(i) * (UInt64)Math.Pow(31, i);         if (lowTolerance) i += 2;         else i++;     }     return hashedValue; } 
like image 920
P basak Avatar asked Mar 03 '12 11:03

P basak


People also ask

Which hash function is fastest?

SHA-1 is fastest hashing function with ~587.9 ms per 1M operations for short strings and 881.7 ms per 1M for longer strings. MD5 is 7.6% slower than SHA-1 for short strings and 1.3% for longer strings.

Is there a hash function in C?

A Hash Table in C/C++ (Associative array) is a data structure that maps keys to values. This uses a hash function to compute indexes for a key. Based on the Hash Table index, we can store the value at the appropriate location.

Which string hashing is best?

If you just want to have a good hash function, and cannot wait, djb2 is one of the best string hash functions i know. it has excellent distribution and speed on many different sets of keys and table sizes. you are not likely to do better with one of the "well known" functions such as PJW, K&R[1], etc.


1 Answers

static UInt64 CalculateHash(string read) {     UInt64 hashedValue = 3074457345618258791ul;     for(int i=0; i<read.Length; i++)     {         hashedValue += read[i];         hashedValue *= 3074457345618258799ul;     }     return hashedValue; } 

This is a Knuth hash. You can also use Jenkins.

like image 82
David Schwartz Avatar answered Sep 20 '22 01:09

David Schwartz