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
https://forums.phpfreaks.com/topic/237190-in_array-very-slow-performance/
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;
   }
}

@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;
    }

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.