最近看书,里面提到了一些Hash算法。比较有印象的是Times33,当时理解不是很透测,今天写了段程序来验证了一下。
代码如下:
<?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<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);
以上有两个测试用例。第一个,用CRC32的方法;第二个是Times33的算法实现。
效果:
结果分布,两种算法不相上下(估计是数据源的问题,md5只有0-f)。也有文章说CRC32的分布更均匀(参考链接:)
但耗费时间,CRC32比Times33快将近一倍。
为什么是33?
即是素数(质数),也是奇数。除了33,还有131, 1313, 5381等。PHP内置的Hash函数用的是5381,在“鸟哥”的一篇博文中也有提到。
【相关教程推荐】
2. php从入门到精通
3. bootstrap教程

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
