PHP hash algorithm: TIMES33 algorithm code example
This article mainly introduces the PHP hash algorithm: TIMES33 algorithm code example, this article directly give the implementation code, the need for friends can refer to the next
Recently read a book, the inside mentioned some hash algorithm. The more impressive is the Times33, at that time understanding is not very test, today wrote a paragraph program to verify a bit.
First on the code:
Copy the code code as follows:
/**
* CRC32 Hash function
* @param $str
* @return int
*/
function Hash32 ($STR)
{
return Crc32 ($STR) >> & 0x7FFFFFFF;
}
/**
* Times33 Hash function
* @param $str
* @return int
*/
function hash33 ($STR)
{
$hash = 0;
for ($i =0; $i
$hash + = * $hash + ord ($str {$i});
}
return $hash & 0x7FFFFFFF;
}
$n = 10;
Test Case 1
$stat = Array ();
for ($i =0; $i <10000; $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 <10000; $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);
There are two test cases above. The first one, using the CRC32 method, the second is the TIMES33 algorithm implementation.
Effect:
The results are distributed, and the two algorithms are equal (estimation is the problem of data source, MD5 only 0-f). There are also articles saying that the distribution of CRC32 is more uniform (see Links:)
But time-consuming, CRC32 is nearly a fold faster than TIMES33.
Why is it 33?
That is the prime number (prime number), which is also odd. In addition to 33, there are 131, 1313, 5381 and so on. PHP built-in hash function is 5381, in the "Brother Bird" in a blog post also mentioned.
http://www.bkjia.com/PHPjc/1000082.html www.bkjia.com true http://www.bkjia.com/PHPjc/1000082.html techarticle PHP hash algorithm: TIMES33 algorithm code example this article mainly introduces the PHP hash algorithm: TIMES33 algorithm code example, this article directly gives the implementation code, the need for friends can refer to the recent look ...