为什么"hash('md5','string')"比"md5('string')"更快?

Pim*_*Pim 12 php hash md5

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

有什么可以解释这种差异?md5()功能有何不同和/或更多?

Bab*_*aba 5

是100%正确的 ......那是,如果你还在使用PHP的早期版本PHPPHP 5.1.2PHP 5.2.2在最反感稳定版本的PHP,他们是相同的,md5稍微有些版本运行速度更快

这是大多数PHP版本中的简单测试

你还需要注意,基准测试方法是错误的,改变位置会影响结果...这是如何获得更好的结果.

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>';
Run Code Online (Sandbox Code Playgroud)

产量

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

)
Run Code Online (Sandbox Code Playgroud)

现场测试


One*_*rew 2

有一样的!!!你需要用大字符串来测试它来检查它,我使用这个代码:

<?php

$s="";
for ($i=0;$i<1000000;$i++)
$s.=$i;
$time=microtime(1);
   hash('md5', $s);
echo microtime(1)-$time,': hash/md5<br>';

$time=microtime(1);

 md5($s);
echo microtime(1)-$time,': md5<br>';

$time=microtime(1);
hash('sha1', $s);
echo microtime(1)-$time,': hash/sha1<br>';

$time=microtime(1);
sha1($s);
echo microtime(1)-$time,': sha1<br>';
?>
Run Code Online (Sandbox Code Playgroud)

这是我的结果:

0.015523910522461: hash/md5
0.01521897315979: md5
0.020196914672852: hash/sha1
0.020323038101196: sha1
Run Code Online (Sandbox Code Playgroud)

非常相似!!!

  • 在 PHP 内部运行这些类型的基准测试..使用解释型 PHP 是毫无意义的。您使用的 PHP 版本与 6 年前使用的版本相同吗?您应该直接转到源代码并解释 hash 和 md5 之间的差异 https://github.com/php/php-src/blob/master/ext/hash/hash.c#L126。你反驳了这个理论,但你没有解释任何事情。 (2认同)