[PHP]md5, sha1, crc32の中で最も長いハッシュ値を返す関数はどれ?

PHPでは値のハッシュ値を求めるために、md5(), sha1(), crc32()など、複数の関数が用意されています。

各ハッシュ関数はそれぞれ下記の長さのハッシュ値を返し、3つの中ではsha1()が最も長いです。
[md5] 32byte
[sha1] 40byte
[crc32] 10byte


これは、下記のコードで確認できます。

$md5Val   = md5( "a" );
$sha1Val  = sha1( "a" );
$crc32Val = crc32( "a" );
 
printf( "[md5]   %dbyte : %s\n", strlen( $md5Val ), $md5Val );
printf( "[sha1]  %dbyte : %s\n", strlen( $sha1Val ), $sha1Val );
printf( "[crc32] %dbyte : %s\n", strlen( $crc32Val ), $crc32Val );



実行結果:

[vagrant@localhost php]$ php test01.php
[md5]   32byte : 0cc175b9c0f1b6a831c399e269772661
[sha1]  40byte : 86f7e437faa5a7fce15d1ddcb9eaeaea377667b8
[crc32] 10byte : 3904355907





一方で、実行速度を比較すると、当然ながら長い文字列を返すsha1()の方が遅いです。

$start = microtime(true);
for( $i = 0; $i<1000000; $i++ ) {
    $md5Val   = md5( "a" );
}
echo microtime(true) - $start . "\n";
 
 
$start = microtime(true);
for( $i = 0; $i<1000000; $i++ ) {
    $sha1Val  = sha1( "a" );
}
echo microtime(true) - $start . "\n";
 
 
$start = microtime(true);
for( $i = 0; $i<1000000; $i++ ) {
    $crc32Val = crc32( "a" );
}
echo microtime(true) - $start . "\n";




それぞれ、100万回づつ実行させてみたところ、下記の時間が掛かりました。

[vagrant@localhost php]$ php test01.php
[md5]   0.72834014892578
[sha1]  0.95457792282104
[crc32] 0.33486604690552


関連記事

コメントを残す

メールアドレスが公開されることはありません。