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
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)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.