最近看书,里面提到了一些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教程
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Assassin's Creed Shadows: Seashell Riddle Solution
2 weeks agoByDDD
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

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