php - Code take too long to process and has a big memory footprint -


this code executes in 0.8seconds , takes 22mb of memory on machine.

   $x=500;    $y=500;     $im = imagecreatetruecolor($x,$y);    $ia=array();    ($i = 0; $i < $x; $i++) {     ($j = 0; $j < $y; $j++) {         $r=rand(0,96);         $g=rand(0,128);         $b=rand(0,255);         $ia[$i][$j]=imagecolorallocate($im,$r,$g,$b);     }    } 

what can done speed up, more importantly lower memory footprint eats @ given time.

try following code (from http://php.net/manual/en/function.imagecolorallocate.php) instead of direct colour assignment:

function createcolor($pic,$c1,$c2,$c3) {    $color = imagecolorexact($pic, $c1, $c2, $c3);    if($color==-1) {       if(imagecolorstotal($pic)>=1000) {          $color = imagecolorclosest($pic, $c1, $c2, $c3);       } else {          $color = imagecolorallocate($pic, $c1, $c2, $c3);       }    }    return $color;  } 

also, try making function call in 1 line:

$ia[$i][$j] = createcolor($im, mt_rand(0,96), mt_rand(0,128), mt_rand(0,255)); 

fiddle hardcoded value 1000, , see how changes memory usage.


Comments