PHP Hash algorithm: Times33 algorithm code example, hashtimes33
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:
Copy codeThe Code is as follows:
<? Php
/**
* 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 <strlen ($ str); $ I ++ ){
$ Hash + = 33 * $ hash + ord ($ str {$ I });
}
Return $ hash & 0x7FFFFFFF;
}
$ N = 10;
// Test Case 1
$ Stat = array ();
For ($ I = 0; I 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 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.