Jump to content

in_array() very slow performance


JustinK101

Recommended Posts

I have the following simple code to test against collision on a primary key I am creating:

 

        $machine_ids = array();
for($i = 0; $i < 100000; $i++) {
	//Generate machine id returns a 15 character alphanumeric string
                $mid = Functions::generate_machine_id();

	if(in_array($mid, $machine_ids)) {
		die("Collision!");
	} else {
		$machine_ids[] = $mid;	
	}
}

die("Success!");

 

Any idea why this is taking minutes to run? Anyway to speed it up?

Link to comment
Share on other sites

The generator algorithm inst the problem, ran the code without the check and under a second. I know I am checking 100,000. That's the entire point. Honestly, 100,000 element array inst that much in today's scale.

Link to comment
Share on other sites

Stackoverflow to the rescue, here is the solution, runs in 2 seconds.

 

for($i = 0; $i < 100000; $i++) 
{
  //Generate machine id returns a 15 character alphanumeric string
  $mid = Functions::generate_machine_id();
   if (isset($machine_ids[$mid])) {
       die("Collision!");
   } else {
      $machine_ids[$mid] = true;
   }
}

Link to comment
Share on other sites

@gizmola

 

Here is the function you wanted to see by the way. No wizardry, just fast.

 

public static function generate_machine_id($length = 15) {
		$password = "";
		$possible = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    	$maxlength = strlen($possible);
    	
    	if ($length > $maxlength) {
      		$length = $maxlength;
    	}
    	
    	$i = 0;
    	
    	while ($i < $length) {
     		$password .= substr($possible, mt_rand(0, $maxlength-1), 1);
       		$i++;
    	}
    	
    	return $password;
    }

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.