This article mainly introduced the PHP hash algorithm: TIMES33 algorithm code example, this article directly gives the realization code, needs the friend may refer to under
Recently read a book, which mentions some hash algorithm. More impressive is Times33, at that time understanding is not very penetrating test, today wrote a section of the program to verify a bit.
First code:
Copy 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 is to use the CRC32 method and the second is to implement the TIMES33 algorithm.
Effect:
The result distribution, two algorithms are equal (estimate is the problem of data source, MD5 only 0-f). There are also articles saying that the distribution of CRC32 is more uniform (reference link:)
But time consuming, CRC32 is nearly one times faster than TIMES33.
Why is it 33?
That is the prime number (prime number), is also odd. In addition to 33, there are 131, 1313, 5381 and so on. PHP's built-in hash function is 5381, which is also mentioned in a blog post in "Brother Bird".