PHPHash algorithm: Times33 algorithm code example _ PHP-php Tutorial

Source: Internet
Author: User
Tags crc32
This article mainly introduces the PHPHash algorithm: Times33 algorithm code example. This article provides the implementation code directly. if you need it, you can refer to the latest book, which mentions 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:

The 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 $ 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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.