前几天google了一些php的hash函数, 想找到一种分布较为均匀的hash算法, 这样对于比如数据库分表或者其他一些需要hash的场景比较有帮助. 然后就发现了这个Another happy memcached user. 很多hash函数采用times 33, 下边是php的实现: function hash_func1($ke
前几天google了一些php的hash函数, 想找到一种分布较为均匀的hash算法, 这样对于比如数据库分表或者其他一些需要hash的场景比较有帮助. 然后就发现了这个Another happy memcached user.
很多hash函数采用times 33, 下边是php的实现:
function hash_func1($key, $n) { $hash = 0; for ($i = 0; $i <p>而上边链接的邮件中提到了一种分布更均匀的算法, 如下:</p> <pre class="brush:php;toolbar:false">function hash_func(&$keyword, $n) { $hash = crc32($keyword) >> 16 & 0x7fff; return $hash % $n; }
为了自己验证下, 我整理了一套cet-4词汇表来做测试. 测试结果如下, 使用time 33
<code>bash$ time php h.php bucket(0): 11.33% bucket(1): 9.61% bucket(2): 10.23% bucket(3): 9.77% bucket(4): 9.85% bucket(5): 9.81% bucket(6): 10.21% bucket(7): 9.50% bucket(8): 9.70% bucket(9): 9.99% real 0m0.026s user 0m0.006s sys 0m0.003s </code>
使用crc32移位的这个,
<code>bash$ time php h.php bucket(0): 10.16% bucket(1): 10.52% bucket(2): 9.72% bucket(3): 9.79% bucket(4): 9.54% bucket(5): 10.34% bucket(6): 9.21% bucket(7): 10.45% bucket(8): 10.12% bucket(9): 10.14% real 0m0.015s user 0m0.003s sys 0m0.002s </code>
从测试结果来看, 使用crc32移位的hash方法要比times 33分布更为均匀一些, 并且效率也要高一些. 测试的php代码和cet4词汇表: 点击这里下载. 感兴趣的可以自己测试一下.
原文地址:PHP: 分布均匀的hash函数, 感谢原作者分享。

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

Atom editor mac version download
The most popular open source editor

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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