Jump to content

Most efficient random string method


plznty

Recommended Posts

currently using

function gen_chars($length = 6) {
    // Available characters
    $chars = '0123456789abcdefghjkmnoprstvwxyz';

    $Code  = '';
    // Generate code
    for ($i = 0; $i < $length; ++$i)
    {
        $Code .= substr($chars, (((int) mt_rand(0,strlen($chars))) - 1),1);
    }
return $Code;
}

// Usage
$var = gen_chars(12);

echo $var;

 

However ide like to know if theres a more efficient way of generating this since this is going to be using a lot.

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/217153-most-efficient-random-string-method/
Share on other sites

In my test this was about 15% faster then your original - it eliminates a bunch of calls to strlen.

 

function gen_chars($length = 6) {
    // Available characters
    $chars = '0123456789abcdefghjkmnoprstvwxyz';
    $len = strlen($chars);

    $Code  = '';
    // Generate code
    for ($i = 0; $i < $length; ++$i)
    {
        $Code .= substr($chars, ((mt_rand(0,$len)) - 1),1);
    }
return $Code;
}

 

However, this was about twice as fast (for whatever reason)!

 

function gen_chars($length = 6) {
   // Available characters
   $chars = '0123456789abcdefghjkmnoprstvwxyz';
   $charsarray = str_split($chars);
   $len = strlen($chars)-1;

   $Code  = '';
   // Generate code
   for ($i = 0; $i < $length; ++$i) {
       $Code .= $charsarray[(mt_rand(0,$len))];
   }
}

 

Of course, I tested building a string 500,000 characters long, so if you are only building short strings then yours will be faster! (less overhead)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.