note 84994 deleted from function.rand by bjori
| From: | bjori@php.net | Date: | Sat, 09 Aug 2008 17:15:55 +0000 |
| Subject: | note 84994 deleted from function.rand by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-143325@lists.php.net to get a copy of this message | ||
Note Submitter: Jase Taylor
----
Random password generation isn't probably something we link with processing speed
I created 3 functions (all 3 were tested with both mt_rand() and rand())
the first sets all the characters in a string
ie
$str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
then uses a for loop (for use with dynamic password length) to run through using substr to create
the "random password"
The second function does the same but instead of using substr, it uses this syntax $str{$rand} to
get the random character
the third function used char(). 3 rands were needed for this, one for numeric, one for lowercase and
one for uppercase and then another rand used to pick which of those 3 to use
I performed 1,000,000 tests on each function and then took the average execution time of each
function
function 2 was over 2 times faster than function 3
function 2 was also just over 0.5 times faster than function one
So for the fastest way to generate a random password is to use the $str{} syntax
here is the function that did 1,000,000 passwords each of which were 50 characters in length in
0.00063 seconds per function execution
function pass_gen($pass_length)
{
$str = '012345679abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$pass = '';
$str_len = strlen($str) -1;
for($i=0; $i < $pass_length; $i++)
{
$rand = mt_rand(0, $str_len);
$pass .=$str[$rand];
}
return $pass;
}
echo "\n";
echo pass_gen(10);
echo "\n";
which outputs : v2vH0SdpZy