Abstract:
Benchmark program for hash tables and comparison of 15 popular hash functions.

Created 2 years ago by Peter Kankowski
Last changed 3 months ago
Contributors: Nils, Ace, and Won
Filed under Algorithms

Reddit Digg Delicious Buzz Facebook Twitter

Hash functions: An empirical comparison

Hash tables are popular data structures for storing key-value pairs. A hash function is used to map the key value (usually a string) to array index. The functions are different from cryptographic hash functions, because they should be much faster and don't need to be resistant to preimage attack. There are two classes of the functions used in hash tables:

Hash table benchmarks usually include theoretical metrics such as the number of collisions or distribution uniformity (see, for example, hash function comparison in the Red Dragon book). Obviously, you will have a better distribution with more complex functions, so they are winners in these benchmarks.

The question is whether using complex functions gives you a faster program. The complex functions require more operations per one key, so they can be slower. Is the price of collisions high enough to justify the additional operations?

Multiplicative hash functions

Any multiplicative hash function is a special case of the following algorithm:

UINT HashMultiplicative(const CHAR *key, SIZE_T len) {
   UINT hash = INITIAL_VALUE;
   for(UINT i = 0; i < len; ++i)
      hash = M * hash + key[i];
   return hash % TABLE_SIZE;
}

(Sometimes XOR operation is used instead of addition, but it does not make much difference.) The hash functions differ only by values of INITIAL_VALUE and multiplier (M). For example, the popular Bernstein's function uses INITIAL_VALUE of 5381 and M of 33; Kernighan and Ritchie's function uses INITIAL_VALUE of 0 and M of 31.

A multiplicative function works by adding together the letters weighted by powers of multiplier. For example, the hash for the word TONE will be:

  INITIAL_VALUE * M^4  +  'T' * M^3  +  'O' * M^2  +  'N' * M  +  'E'

Let's enter several similar strings and watch the output of the functions:

     Bernstein Kernighan
        (M=33)     (M=31)
 too   b88af17     1c154
 top   b88af18     1c155
 tor   b88af1a     1c157
 tpp   b88af39     1c174
a000  7c9312d6    2cd22f
a001  7c9312d7    2cd230
a002  7c9312d8    2cd231
a003  7c9312d9    2cd232
a004  7c9312da    2cd233
a005  7c9312db    2cd234
a006  7c9312dc    2cd235
a007  7c9312dd    2cd236
a008  7c9312de    2cd237
a009  7c9312df    2cd238
a010  7c9312f7    2cd24e
   a     2b606        61
  aa    597727       c20
 aaa   b885c68     17841

Too and top are different in the last letter only. The letter P is the next one after O, so the values of hash function are different by 1 (1c154 and 1c155, b88af17 and b88af18). Ditto for a000..a009.

Now let's compare top with tpp. Their hashes will be:

  INITIAL_VALUE * M^3 + 'T' * M^2 + 'O' * M + 'P'
  INITIAL_VALUE * M^3 + 'T' * M^2 + 'P' * M + 'P'

The hashes will be different by M * ('P' - 'O') = M. Similarly, when the first letters are different by x, their hashes will be different by x * M^2.

When there are less than 33 possible letters, Bernstein's function will pack them into a number (similar to Radix40 packing scheme). For example, hash table of size 333 will provide perfect hashing (without any collisions) for all three-letter English words written in small letters. In practice, the words are longer and hash tables are smaller, so there will be some collisions (situations when different strings have the same hash value).

If the string is too long to fit into the 32-bit number, the first letters will still affect the value of the hash function, because the multiplication is done modulo 2^32 (in a 32-bit register), and the multiplier is chosen to have no common divisors with 2^32 (in other words, it must be odd), so the bits will not be just shifted away.

There are no exact rules for choosing the multiplier, only some heuristics:

Complex hash functions

These functions do a good job of mixing together the bits of the source word. The change in one input bit changes a half of the bits in the output (see Avalanche_effect), so the result looks completely random:

     Paul Hsieh One At Time
 too   3ad11d33  3a9fad1e  
 top   78b5a877  4c5dd09a  
 tor   c09e2021  f2aa9d35  
 tpp   3058996d  d5e9e480  
a000   7552599f  ed3859d8  
a001   3cc1d896  fef7fd57  
a002   c6ff5c9b  08a610b3  
a003   dcab7b0c  1a88b478  
a004   780c7202  3621ebaa  
a005   7eb63e3a  47db8f1d  
a006   6b0a7a17  b901717b  
a007   cb5cb1ab  caec1550  
a008   5c2a15c0  e58d4a92  
a009   33339829  f75aee2d  
a010   eb1f336e  bd097a6b  
   a   115ea782  ca2e9442  
  aa   008ad357  7081738e  
 aaa   7dfdc310  ae4f22ec

To achieve this behavior, the hash functions perform a lot of shifts, XORs, and additions. But do we need a complex function? What is faster: tolerating the collisions and resolving them with chaining, or avoiding them with a more complex function?

Test conditions

The benchmark uses separate chaining algorithm for collision resolution. Memory allocation and other "heavy" functions were excluded from the benchmarked code. The RDTSC instruction was used for benchmarking. The test was performed on Pentium-M and Core i5 processors.

The benchmark inserts some keys in the table, then looks them up in the same order as they were inserted. The test data include:

Results

Core i5 processor

WordsWin32NumbersPrefixPostfixVariablesSonnetsUTF-8IPv4Avg
iSCSI CRC69[105]349[415]39[112]92[106]90[92]295[368]429[584]2075[2388]332[838]1.01[1.75]
Murmur277[103]406[415]52[104]117[106]113[111]337[383]488[566]2337[2399]426[834]1.21[1.72]
Paul Larson79[99]436[416]39[16]150[99]150[105]342[366]489[583]2411[2447]379[755]1.26[1.08]
CRC-3275[101]452[426]44[64]153[107]150[94]339[338]473[563]2327[2400]382[725]1.27[1.39]
Novak unrolled81[113]429[399]48[90]136[118]133[113]345[342]493[581]2428[2430]410[969]1.27[1.66]
Sedgewick79[107]441[414]44[48]152[103]151[103]340[348]489[570]2412[2437]394[782]1.29[1.30]
FNV-1a80[124]438[428]51[108]149[94]150[105]338[374]482[555]2383[2446]409[807]1.30[1.75]
x6559990[111]425[382]49[203]149[107]149[122]338[379]482[560]2376[2373]378[846]1.30[2.42]
Fletcher76[131]374[406]89[460]110[127]106[108]330[507]508[1052]2605[4893]415[1359]1.30[4.59]
Paul Hsieh84[114]427[420]59[118]129[101]126[100]351[341]518[600]2443[2380]468[847]1.31[1.80]
Bernstein91[114]447[412]56[288]158[100]157[102]339[353]483[572]2412[2380]385[703]1.35[2.96]
K&R90[106]453[437]54[288]157[94]157[106]345[360]484[561]2422[2365]375[831]1.35[2.98]
x17 unrolled95[109]467[415]49[24]164[113]161[102]363[368]502[589]2502[2392]404[829]1.38[1.17]
lookup392[101]496[412]60[97]149[101]148[95]389[361]570[550]2655[2392]474[834]1.44[1.63]
Ramakrishna89[108]544[409]51[91]201[125]198[103]399[360]540[528]2783[2383]422[840]1.54[1.63]
One At Time90[105]588[421]62[110]228[97]226[103]414[364]547[545]2816[2346]489[795]1.68[1.72]
Arash Partow91[101]583[435]78[420]221[98]217[85]420[355]544[570]2799[2372]448[779]1.70[3.86]
Weinberger89[104]627[422]42[100]258[111]279[117]424[364]551[712]2882[2547]454[744]1.74[1.73]
Two chars65[182]369[1265]184[490]120[351]91[310]459[1454]688[2706]7410[12584]406[1657]1.89[6.70]
Hanson78[118]432[649]48[112]127[118]1630[499]330[435]474[592]2384[2890]386[833]3.08[2.43]

Pentium-M processor

WordsWin32NumbersPrefixPostfixVariablesSonnetsUTF-8IPv4Avg
Novak unrolled100[113]547[399]63[90]185[118]175[113]430[342]622[581]2949[2430]544[969]1.09[1.66]
CRC-32101[101]592[426]61[64]209[107]200[94]457[338]650[563]3091[2400]506[725]1.14[1.39]
Murmur2109[103]576[415]74[104]182[106]177[111]481[383]688[566]3229[2399]601[834]1.18[1.72]
x17 unrolled105[109]634[415]64[24]231[113]220[102]479[368]662[589]3184[2392]575[829]1.22[1.17]
Paul Larson106[99]662[416]56[16]244[99]238[105]494[366]670[583]3341[2447]531[755]1.24[1.08]
x65599107[111]662[382]71[203]245[107]239[122]499[379]666[560]3341[2373]531[846]1.27[2.42]
Fletcher97[131]484[406]175[460]155[127]144[108]429[507]682[1052]3346[4893]633[1359]1.29[4.59]
lookup3112[101]635[412]85[97]213[101]205[95]499[361]733[550]3358[2392]691[834]1.30[1.63]
Bernstein111[114]690[412]80[288]252[100]248[102]507[353]679[572]3406[2380]556[703]1.32[2.96]
K&R112[106]689[437]77[288]251[94]245[106]511[360]696[561]3446[2365]539[831]1.32[2.98]
Paul Hsieh125[114]644[420]94[118]205[101]197[100]525[341]794[600]3638[2380]759[847]1.36[1.80]
Ramakrishna118[108]757[409]69[91]293[125]281[103]549[360]716[528]3647[2383]575[840]1.41[1.63]
FNV-1a119[124]760[428]76[108]287[94]281[105]546[374]722[555]3616[2446]621[807]1.43[1.75]
Sedgewick120[107]784[414]73[48]297[103]292[103]567[348]753[570]3787[2437]636[782]1.47[1.30]
One At Time126[105]821[421]88[110]310[97]303[103]594[364]792[545]4001[2346]705[795]1.57[1.72]
Arash Partow119[101]790[435]135[420]298[98]289[85]566[355]751[570]3712[2372]625[779]1.59[3.86]
Weinberger128[104]987[422]62[100]392[111]389[117]658[364]805[712]4271[2547]621[744]1.70[1.73]
Two chars93[182]547[1265]475[490]236[351]152[310]966[1454]1514[2706]19351[12584]556[1657]2.84[6.70]
Hanson101[118]587[649]63[112]185[118]4361[499]444[435]626[592]3113[2890]512[833]4.33[2.43]

Each cell includes the execution time, then the number of collisions in square brackets. Execution time is expressed in thousands of clock cycles (a lower number is better). Avg column contains the average normalized execution time (and the number of collisions).

The function by Kernighan and Ritchie is from their famous book "The C programming Language", 3rd edition; Weinberger's hash and the hash with multiplier 65599 are from the Red Dragon book. The latter function is used in gawk, sdbm, and other Linux programs. x17 is the function by Peter Kankowski (multiplier = 17; 32 is subtracted from each letter code).

As you can see from the table, the function with the lowest number of collisions is not always the fastest one.

Conclusion

Complex functions by Paul Hsieh and Bob Jenkins are tuned for long keys, such as the ones in postfix and prefix tests. Note that they do not provide the best number of collisions for these tests, but do have the best time, which means that the functions are faster than the others because of loop unrolling. At the same time, they are suboptimal for short keys (words and sonnets tests).

For a word counting program, a compiler, or another application that typically handles short keys, it's often advantageous to use a simple multiplicative function such as x17 or Larson's hash. However, these functions perform badly on long keys.

Murmur2, CRC32, and Novak unrolled provide good performance for all kinds of keys. They can be recommended as general-purpose hashing functions.

Hardware-accelerated CRC (labeled iSCSI CRC in the table) is the fastest hash function on the recent Core i5/i7 processors. However, the CRC32 instruction is not supported by AMD and earlier Intel processors.

Download the source code (144 KB, MSVC++)

Variations

XORing high and low part

For table size less than 2^16, we can improve the quality of hash function by XORing high and low words, so that more letters will be taken into account:

   return hash ^ (hash >> 16);

Subtracting a constant

x17 hash function subtracts a space from each letter to cut off the control characters in the range 0x00..0x1F. If the hash keys are long and contain only Latin letters and numbers, the letters will be less frequently shifted out, and the overall number of collisions will be lower. You can even subtract 'A' when you know that the keys will be only English words.

Using larger multipliers for a compiler

Paul Hsieh noted that large multipliers may provide better results for the hash table in a compiler, because a typical source code contains a lot of one-letter variable names (i, j, s, etc.), and they will collide if the multiplier is less than the number of letters in the alphabet.

The test confirms this assumption: the function by Kernighan & Ritchie (M = 33) has lower number of collisions than x17 (M = 17), but the latter is still faster (see Variables column in the table above).

Setting hash table size to a prime number

A test showed that the number of collisions will usually be lower if you use a prime, but the calculations modulo prime take much more time than the calculations for a power of 2, so this method is impractical. Even replacing division with multiplication by reciprocal values do not help here:

WordsWin32NumbersPrefixPostfixVariablesShakespeare
Bernstein % 2K145[261]880[889]426[8030]326[214]316[226]649[697]874[1131]
Bernstein % prime186[221]1049[995]445[5621]364[194]357[217]805[800]1123[1051]
Bernstein optimized mod160[221]960[995]416[5621]341[194]334[217]722[800]969[1051]
x17 % 2K137[193]847[1002]81[340]314[244]300[228]641[863]832[1012]
x17 % prime173[256]1010[1026]104[324]356[246]339[216]760[760]1046[1064]
x17 optimized mod155[256]915[1026]96[324]330[246]315[216]691[760]930[1064]

Implementing open addressing vs. separate chaining

With open addressing, most hash functions show awkward clustering behavior in "Numbers" test:

Bernst.K&Rx17 unrollx65599FNVUnivWeinb.HsiehOne-atLookup3PartowCRC
OA4268184207889127311010392104279
[8030][20810][340][3158][207][480][4360][342][267][205][20860][96]
32-bit17969741148680125105999234782
[8030][20810][340][3158][207][480][4360][342][267][205][20860][96]
chain92687382888473107999514984
[500][500][24][258][124][48][100][138][131][108][1530][64]

You can avoid the worst case by using chaining for collision resolution. However, chaining requires more memory for the next item pointers, so the performance improvement does not come for free. A custom memory allocator should be usually written, because calling malloc() for a large number of small structures is suboptimal.

Some implementations (e.g., hash table in Python interpreter) store a full 32-bit hash with the item to speed up the string comparison, but this is less effective than chaining.

101 comments

Ten recent comments are shown below. Show all comments

Peter Kankowski, 4 months ago

Andrew, I've added the tests with UTF-8 and IP addresses (in binary). Fletcher's hash is terrible for UTF-8 texts because of repeated first bytes in multi-byte sequences. I did an additional test with a Russian novel, and Fletcher was even worse. The results of other functions were not very different from the previous tests.

Ace, I've updated Novak hash and x17 (h = 1). AES instructions implement the whole round of encryption, not just substitution using S-boxes.

CRC32 is implemented in Core i5-i7 processors, but with the iSCSI polynomial, so it is useless for ZIP, PNG, MPEG-2, and many other formats, which use a different polynomial. Though it does not matter much for a hash function which polynomial to use. I will probably try accelerated CRC32 later :)

Andrew M., 3 months ago
Have you done the SSE CRC32 testing yet? I want to get an i7 to try it out, but can't justify it since my E8400 is still way too fast.

Could any of the AES instructions be used for hashing too? I can't seem to find any speed comparions for the SSE CRC32/AES instructions at all.
ace, 3 months ago
I believe Andrew that you wouldn't notice some improvement from E8400 unless you can actually use more cores at once.
As Peter linked, AES instructions seem to be too heavy for hashing, as they do much bigger work, which is not surprising, the substitution alone is very effective as soon as the table is in cache.
Peter Kankowski, 3 months ago

I've just done the tests on Core i5 processor (see the results above). Hardware-accelerated CRC is the fastest hash function; x17 is slow on this processor for some reason.

I've also optimized the handling of remaining bytes in your CRC32 code (using two conditions instead of the loop). It's slightly faster this way.

Andrew M., 3 months ago
No, my E8400 doesn't support SSE 4.2 (CRC32/AES instructions) at all! They were introduced with the i7. Otherwise I would have done some benchmarking on them myself.

The hardware CRC32 numbers are fairly impressive. That is why I wondered about AES, if any of the ops are fast enough then they could be quite good.
Peter Kankowski, 3 months ago
I would like to see the AES results, too. Unfortunately, my i5 has no support for AES instructions. If anybody else can do the benchmark, please drop a comment here.
ace, 3 months ago
Andrew, re "unless you really need cores" I was referring to your "can't justify it since my E8400 is still way too fast."

Here's what I've found about the speedup of CPU-accelerated AES compared to non-CPU accelerated AES: it is approximately "just" factor 4, at least according to:

http://wiki.debianforum.de/BenchmarkFestplattenverschlüsselung

and according to Intel, up to 10 for multi-core scenario:

http://software.intel.com/en-us/articles/intel-advanced-encryption-standard-instructions-aes-ni/

As AES-NI instruction does whole round on 16 bytes and there is a lot of processing for one round and the typical speedup is only 4, I believe AES-NI is therefore still irrelevant for the simple kind of hashing that's the subject here.

Peter, do you have then I5-750 instead of any of I5-6*'s (which are all supposed to have AES-NI, at least according to: http://processorfinder.intel.com/List.aspx?ProcFam=3155)?

I didn't know there are I5's without AES-NI at all until now.
Peter Kankowski, 3 months ago

AES-NI results are impressive. As I found, it's supported by PGP, DiskCryptor, and other popular encryption software. GnuPG does not use the hardware acceleration; most likely, because they want to stay portable.

Yes, I have Core i5 750 (four cores, SSE 4.2, but no AES-NI).

P.S. Here is a new article with detailed CRC32 benchmarks.

Alexander, 2 days ago
See some hash tests here (Russian):
http://amsoftware.narod.ru/algo.html
ace, 2 days ago
Your test are very insightful, thanks Alexander.
Your name:
Comment: