How to preallocate memory for an array in PHP?

How to preallocate memory for an array in PHP? I want to pre-allocate space for 351 thousand lengths. The function works when I do not use an array, but if I try to store long values ​​in an array, then this will not work. If I try a simple test loop to populate 351k values ​​with range(), it works. I suspect 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_filland array_padbut they initialize the array for specific values.


Decision:

I used a combination of answers. Kevin's answer worked alone, but I was hoping to prevent problems in the future 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;
+1
4

, PHP (, , ). .

ini_set('memory_limit', '1024M');

PHP script, . php.ini. 1 PHP, PHP .

, :

  • , , - , .
  • ( $x, , ?), unset($x);
+2

PHP Array 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';

0 = > test1

1 = > test2

2 = > test3

+3

:

PHP java.

, , . "" , , , .

, array_fill null ( ), .

(, . , XY? ( ), , . , , )

+2

SplFixedArray. , ( ), .

+1

Source: https://habr.com/ru/post/1629521/


All Articles