Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pre-allocate memory for an array in PHP?

How do I pre-allocate memory for an array in PHP? I want to pre-allocate space for 351k longs. The function works when I don't use the array, but if I try to save long values in the array, then it fails. If I try a simple test loop to fill up 351k values with a range(), it works. I suspect that the array is causing memory fragmentation and then running out of memory.

In Java, I can use ArrayList al = new ArrayList(351000);.

I saw array_fill and array_pad but those initialize the array to specific values.


Solution:

I used a combination of answers. Kevin's answer worked alone, but I was hoping to prevent problems in the future too as the size grows.

ini_set('memory_limit','512M');
$foundAdIds = new \SplFixedArray(100000); # google doesn't return deleted ads. must keep track and assume everything else was deleted.
$foundAdIdsIndex = 0;
// $foundAdIds = array();
$result = $gaw->getAds(function ($googleAd) use ($adTemplates, &$foundAdIds, &$foundAdIdsIndex) { // use call back to avoid saving in memory
  if ($foundAdIdsIndex >= $foundAdIds->count()) $foundAdIds->setSize( $foundAdIds->count() * 1.10 ); // grow the array
  $foundAdIds[$foundAdIdsIndex++] = $googleAd->ad->id; # save ids to know which to not set deleted
  // $foundAdIds[] = $googleAd->ad->id;
like image 323
Chloe Avatar asked Mar 02 '26 01:03

Chloe


1 Answers

PHP has an Array Class with SplFixedArray

$array = new SplFixedArray(3);
$array[1] = 'test1';
$array[0] = 'test2';
$array[2] = 'test3';
foreach ($array as $k => $v) {
    echo "$k => $v\n";
}
$array[] = 'fails';

gives

0 => test1

1 => test2

2 => test3

like image 177
Syed mohamed aladeen Avatar answered Mar 03 '26 14:03

Syed mohamed aladeen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!