分佈均勻的hash函數

PHP API by Ryan Gilfether hash function:

sprintf("%u",crc32($key));

The PHPCA hash function (this is a PHP port of the Perl API function):

function hashfunc ($key)
{
    $hash = 0;
    for ($i=0; $i<strlen($key); $i++)
    {
       $hash = $hash*33 + ord($key[$i]);
    }

    return $hash;
}

I didn't get good bucket distributions with either of these, so I use 
this:

(crc32($key)>>16)&0x7fff;

which is then modulo'd with the number of buckets. For example, with a 
randomly-chosen alphabetic key, the sprintf version consistently 
generates a distribution like this (numbers are rounded):

0 10%
1 9%
2 60%
3 9%
4 9%

In my tests, bucket #2 gets far more of the distribution than the other 
buckets regardless of the number of buckets. But with the shift>>16 
bits version I consistently see more evenly distributed results:

0 19%
1 19%
2 20%
3 20%
4 20%
發佈了23 篇原創文章 · 獲贊 18 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章