Last active
February 26, 2021 07:46
-
-
Save kn007/233d3783385a2d15d0879ee5b6ca7989 to your computer and use it in GitHub Desktop.
performance: mt_rand vs openssl_random_pseudo_bytes vs random_bytes vs uniqid vs uuid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
define('LOOP_COUNT',100000); | |
function create_uuid_v4(){ | |
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', | |
// 32 bits for "time_low" | |
mt_rand(0, 0xffff), mt_rand(0, 0xffff), | |
// 16 bits for "time_mid" | |
mt_rand(0, 0xffff), | |
// 16 bits for "time_hi_and_version", | |
// four most significant bits holds version number 4 | |
mt_rand(0, 0x0fff) | 0x4000, | |
// 16 bits, 8 bits for "clk_seq_hi_res", | |
// 8 bits for "clk_seq_low", | |
// two most significant bits holds zero and one for variant DCE1.1 | |
mt_rand(0, 0x3fff) | 0x8000, | |
// 48 bits for "node" | |
mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) | |
); | |
} | |
$startTime = microtime(true); | |
for($x=0;$x<LOOP_COUNT;$x++) | |
{ | |
// Your content to test | |
$var1 =mt_rand(1000000000000000,9999999999999999); | |
} | |
$endTime = microtime(true); | |
$elapsed = $endTime - $startTime; | |
echo 'mt_rand in: ',$elapsed,"\n"; | |
$startTime = microtime(true); | |
for($x=0;$x<LOOP_COUNT;$x++) | |
{ | |
// Your content to test | |
$var2 = bin2hex(openssl_random_pseudo_bytes(16)); | |
} | |
$endTime = microtime(true); | |
$elapsed = $endTime - $startTime; | |
echo 'openssl_random_pseudo_bytes(16): in ',$elapsed,"\n"; | |
$startTime = microtime(true); | |
for($x=0;$x< LOOP_COUNT;$x++) | |
{ | |
// Your content to test | |
$var3 = bin2hex(random_bytes(16)); | |
} | |
$endTime = microtime(true); | |
$elapsed = $endTime - $startTime; | |
echo 'random_bytes(16) in: ',$elapsed,"\n"; | |
$startTime = microtime(true); | |
for($x=0;$x< LOOP_COUNT;$x++) | |
{ | |
// Your content to test | |
$var4 = uniqid('',true); | |
} | |
$endTime = microtime(true); | |
$elapsed = $endTime - $startTime; | |
echo 'uniqid(\'\',true) in: ',$elapsed,"\n"; | |
for($x=0;$x< LOOP_COUNT;$x++) | |
{ | |
// Your content to test | |
$var5 = create_uuid_v4(); | |
} | |
$endTime = microtime(true); | |
$elapsed = $endTime - $startTime; | |
echo 'create_uuid_v4 in: ',$elapsed,"\n"; | |
echo "\n\n"; | |
echo 'mt_rand: '.$var1."\n"; | |
echo 'openssl_random_pseudo_bytes: '.$var2."\n"; | |
echo 'random_bytes: '.$var3."\n"; | |
echo 'uniqid: '.$var4."\n"; | |
echo 'create_uuid_v4: '.$var5."\n"; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment