PHP hash algorithm: TIMES33 algorithm code example

Source: Internet
Author: User
Tags crc32 hash md5

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".

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.