最快的 hash function

今天在找速度最快的 hash function

不必考慮安全因素

只要速度!!

主要用途是給css, js加上 hash name

找到一個叫 xxhash 的方法

官方的比較表格

比 md5 快了 16 倍啊!!

NameSpeedQualityAuthor
xxHash5.4 GB/s10Y.C.
MurmurHash 3a2.7 GB/s10Austin Appleby
SBox1.4 GB/s9Bret Mulvey
Lookup31.2 GB/s9Bob Jenkins
CityHash641.05 GB/s10Pike & Alakuijala
FNV0.55 GB/s5Fowler, Noll, Vo
CRC320.43 GB/s9
MD5-320.33 GB/s10Ronald L.Rivest
SHA1-320.28 GB/s10

那我也裝起來實驗看看摟

官方列表中有 php7 的 extension

我用 phpbrew 裝起來超方便

 $ phpbrew ext install https://github.com/Megasaxon/php-xxhash                                                                     

一般安裝的話也不難

只是要記得自己加 ini 設定啟用

然後就是寫 benchmark code

<?php
// set no limit memory
ini_set("memory_limit","-1");

// get a large file content
$filePath = file_get_contents('xxx');
$testTime = 10;

$start = microtime(true);

for ($i = 0; $i < $testTime; $i++) {
    md5($filePath);
}

$end = microtime(true);

echo "md5 spend time: " . number_format(($end - $start), 3) . " s";

echo PHP_EOL;

$start = microtime(true);

for ($i = 0; $i < $testTime; $i++) {
    xxhash32($filePath);
}

$end = microtime(true);

echo "xxhash32 spend time: " . number_format(($end - $start), 3) . " s";

結果

 $ php test_xxhash.php                                                  
md5 spend time: 17.705 s
xxhash32 spend time: 1.539 s

實測的結果也的確超過 16 倍!!!

留言

留言功能尚未啟用 — 設定 giscus(GitHub Discussions)後即會顯示。