Whats is the best way to generate uuidv4 in php?
Some people use this: https://github.com/ramsey/uuid
Others can user a system call like file_get_contents('/proc/sys/kernel/random/uuid');
And others just a simple function.
What's the best way? Depending on your needs, of course.
I can use all the option, so I decide to make a benchmark, and I was surprised...
/var/www/kits/html/test.php.html
<?php
require __DIR__.'/../vendor/autoload.php';
function gen_uuidv4(){
return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0,0xffff),mt_rand(0,0xffff),
mt_rand(0,0xffff),
mt_rand(0,0x0fff)|0x4000,
mt_rand(0,0x3fff)|0x8000,
mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff));
}
$i=microtime(true);
for($a=0;$a<1000000;$a++){
file_get_contents('/proc/sys/kernel/random/uuid');
}
$f=microtime(true);
$t1=$f-$i;
echo $t1;
echo '<br>';
$i=microtime(true);
for($a=0;$a<1000000;$a++){
gen_uuidv4(true);
}
$f=microtime(true);
$t2=$f-$i;
echo $t2;
echo '<br>';
$i=microtime(true);
for($a=0;$a<1000000;$a++){
\Ramsey\Uuid\Uuid::uuid4();
}
$f=microtime(true);
$t3=$f-$i;
echo $t3;
T1: 10.762820005417(s) System Call in Ubuntu 14.04
T2: 6.3450520038605(s) simple function
T3: 30.962769985199(s) blotted library
Choose wisely :)
No comments:
Post a Comment