search
Homephp教程php手册PHP: 分布均匀的hash函数

前几天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词汇表: 点击这里下载. 感兴趣的可以自己测试一下.

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

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

mPDF

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

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft