微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 为什么“hash(‘md5′,’string’)”比“md5(‘string’)”快?

http://www.php.net/manual/en/function.hash.php#73792它表示一个测试,显示md5()函数比等效的hash()函数慢约3倍.

什么可以解释这个差异? md5()函数有什么不同和/或更多的作用?

是100%正确的,那就是如果你仍然使用PHP的早期版本的PHP,例如
PHP 5.1.2到PHP 5.2.2在大多数resent稳定版本的PHP他们是一样的,md5在一些版本中运行略快

Here is a simple test in most PHP version

您还需要注意的是,标记法是错误的,位置变化会影响结果…这是如何获得更好的结果.

set_time_limit(0);
echo "<pre>";

function m1($total) {
    for($i = 0; $i < $total; $i ++)
        hash('md5','string');
}

function m2($total) {
    for($i = 0; $i < $total; $i ++)
        md5('string');
}

function m3($total) {
    for($i = 0; $i < $total; $i ++)
        hash('sha1','string');
}

function m4($total) {
    for($i = 0; $i < $total; $i ++)
        sha1('string');
}

function m5($total) {
    for($i = 0; $i < $total; $i ++)
        hash('md5',$i);
}

function m6($total) {
    for($i = 0; $i < $total; $i ++)
        md5($i);
}

function m7($total) {
    for($i = 0; $i < $total; $i ++)
        hash('sha1',$i);
}

function m8($total) {
    for($i = 0; $i < $total; $i ++)
        sha1($i);
}

$result = array(
        'm1' => 0,'m2' => 0,'m3' => 0,'m4' => 0,'m5' => 0,'m6' => 0,'m7' => 0,'m8' => 0
);

$total = 10000;

for($i = 0; $i < 100; ++ $i) {
    foreach ( array_keys($result) as $key ) {
        $alpha = microtime(true);
        $key($total);
        $result[$key] += microtime(true) - $alpha;
    }
}

echo '<pre>';
echo "Single Run\n";
print_r($result);
echo '</pre>';

产量

Single Run
Array
(
    [m1] => 0.58715152740479                 <--- hash/md5/string
    [m2] => 0.41520881652832                 <--- md5/string
    [m3] => 0.79592990875244                 <--- hash/sha1/string
    [m4] => 0.61766123771667                 <--- sha1/string
    [m5] => 0.67594528198242                 <--- hash/md5/$i
    [m6] => 0.51757597923279                 <--- md5/$i
    [m7] => 0.90692067146301                 <--- hash/sha1/$i
    [m8] => 0.74792814254761                 <--- sha1/$i

)

Live Test

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐