PHP: uniqid() speed test

PHP: uniqid() speed test - php,uniqid,test,speed,compare,time There have been several comments in the notes of the uniqid() manual page about uniqid() being very slow. I set off to see for myself if this were true, using several combinations of input. I tried different length prefixes, as well as toggling the function's more_entropy parameter. For those interested, the code looks something like this:

<?php	
    function microtime_float() {	
        list($usec, $sec) = explode(" ", microtime());	
        return ((float)$usec + (float)$sec);	
    }	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("longprefix");	
    }	
    echo "Long prefix: ".(microtime_float()-$s)."\n";	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("s");	
    }	
    echo "Short prefix: ".(microtime_float()-$s)."\n";	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("");	
    }	
    echo "No prefix: ".(microtime_float()-$s)."\n";	
    	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("longprefix",true);	
    }	
    echo "Long prefix (More Entropy): ".(microtime_float()-$s)."\n";	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("s",true);	
    }	
    echo "Short prefix (More Entropy): ".(microtime_float()-$s)."\n";	
    	
    $s = microtime_float();	
    for($i=0;$i<1000;$i++) {	
        uniqid("",true);	
    }	
    echo "No prefix (More Entropy): ".(microtime_float()-$s)."\n";	
?>


And after about 20 trials, the results look something like this:

image

The y axis being the number of seconds to do 1000 iterations of the function, and the x axis being trial number (funky decimals due to the fact that they're evenly spaced.)

As you can see, simply setting more_entropy makes a world of difference. Prefix appears to not have much effect, but the 3 sets with more_entropy set to true were always faster than the three without it. more_entropy has the added bonus of producing a "more unique" result, according to the manual.
Tags: php, uniqid, test, speed, compare, time

Comments

I just updated the note. I initially had posted the code to something else (Something completely unrelated, in fact.), but I caught my error hopefully before anyone saw it.
By T.J. 09/14/07 04:45:07

Thanks for this. I was about to have to do these tests myself (after reading the same manual page), and you did a great job of it.
By conrad 11/27/07 08:21:49

Wow, great work. much thanks for making this.
By Dave 06/23/08 08:28:53

Add Comment

Please note that your IP address is logged for security purposes and that if you spam, your IP will be blocked from accessing this site.
Name:
URL:
Comment:
The following bbcode is allowed: [b] [i] [s] [url=(url)]link title[/url] [code]

ReCAPTCHA: