I recently read a book about some Hash algorithms. I was quite impressed with Times33. At that time, it was not a thorough test. Today I wrote a program to verify it. First run the code :? Php *** CRC32Hashfunction * @ param $ str * @ returnint * functionhash32 ($ str) {returncrc32 ($ str) 160x7FFFFFFF ;}
I recently read a book about some Hash algorithms. I was quite impressed with Times33. At that time, it was not a thorough test. Today I wrote a program to verify it. First run the code :? Php/*** CRC32Hashfunction * @ param $ str * @ returnint */function hash32 ($ str) {return crc32 ($ str) 16 0x7FFFFFFF ;}
I recently read a book about some Hash algorithms. I was quite impressed with Times33. At that time, it was not a thorough test. Today I wrote a program to verify it.
First run the Code:
/**
* 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<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);
The preceding two test cases are available. First, use the CRC32 method, and the second is the Times33 algorithm.
Effect:
Result distribution. The two algorithms are equal (md5 is only 0-f ). Some articles have said that the distribution of CRC32 is more even (reference link :)
However, it takes nearly twice as long as CRC32 is faster than Times33.
Why is it 33?
It is a prime number (prime number) and an odd number. In addition to 33, 131,131, 5381, and so on. PHP's built-in Hash function uses 5381, which is also mentioned in a blog post on "laruence:
Original article address: PHP Hash algorithm: Times33. Thank you for sharing it with the original author.