前几天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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

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

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.