Home  >  Article  >  Backend Development  >  PHP Hash算法:Times33算法代码实例_PHP

PHP Hash算法:Times33算法代码实例_PHP

WBOY
WBOYOriginal
2016-06-01 11:05:451072browse

最近看书,里面提到了一些Hash算法。比较有印象的是Times33,当时理解不是很透测,今天写了段程序来验证了一下。
先上代码:

代码如下:


/**
 * CRC32 Hash function
 * @param $str
 * @return int
 */
function hash32($str)
{
    return crc32($str) >> 16 & 0x7FFFFFFF;
}

/**
 * Times33 Hash function
 * @param $str
 * @return int
 */
function hash33($str)
{
    $hash = 0;
    for($i=0; $i         $hash += 33 * $hash + ord($str{$i});
    }
    return $hash & 0x7FFFFFFF;
}


$n = 10;

// Test Case 1
$stat = array();
for($i=0; $i     $str = substr(md5(microtime(true)), 0, 8);
    $p = hash32($str) % $n;
    if(isset($stat[$p])){
        $stat[$p]++;
    }else{
        $stat[$p] = 1;
    }
}
print_r($stat);

// Test Case 2
$stat = array();
for($i=0; $i     $str = substr(md5(microtime(true)), 0, 8);
    $p = hash33($str) % $n;
    if(isset($stat[$p])){
        $stat[$p]++;
    }else{
        $stat[$p] = 1;
    }
}
print_r($stat);

以上有两个测试用例。第一个,用CRC32的方法;第二个是Times33的算法实现。

效果:

结果分布,两种算法不相上下(估计是数据源的问题,md5只有0-f)。也有文章说CRC32的分布更均匀(参考链接:)
但耗费时间,CRC32比Times33快将近一倍。

为什么是33?

即是素数(质数),也是奇数。除了33,还有131, 1313, 5381等。PHP内置的Hash函数用的是5381,在“鸟哥”的一篇博文中也有提到。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn