From my tests, your function is already very fast, but I managed to move to a faster one, even if it reduces entropy
fcn time rstr1: 1.074s (slowest) rstr2: 0.917s rstr3: 0.028s (yours) rstr4: 0.022s (mine)
In my script, I needed 1k lines as fast as possible.
function rstr1($length) { // @see http://stackoverflow.com/a/853846/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; return substr(str_shuffle(str_repeat($alphabet, $length)), 0, $length); } function rstr2($length) { // @see http://stackoverflow.com/a/853870/11301 $alphabet='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $str = ''; $count = strlen($alphabet); while ($length--) { $str .= $alphabet[mt_rand(0, $count-1)]; } return $str; } function rstr3($length) { // @see http://stackoverflow.com/q/4757392/11301 $result = null; $replace = array('/', '+', '='); while(!isset($result[$length-1])) { $result.= str_replace($replace, NULL, base64_encode(mcrypt_create_iv($length, MCRYPT_RAND))); } return substr($result, 0, $length); } function rstr4($length) { // uses md5 & mt_rand. Not as "random" as it could be, but it works, and its fastest from my tests return str_shuffle(substr(str_repeat(md5(mt_rand()), 2+$length/32), 0, $length)); } // test the functions for($i=0; $i<1000; $i++){ #$x = rstr1(1024); # #$x = rstr2(1024); # 0.917s #$x = rstr3(1024); # 0.028s #$x = rstr4(1024); # 0.022s #dlog($x); return; }
Quamis
source share