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; }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With