Chl*_*loe 3 php arrays memory-management
如何在 PHP 中为数组预分配内存?我想为 351k long 预先分配空间。当我不使用数组时,该函数可以工作,但如果我尝试在数组中保存长值,则会失败。如果我尝试一个简单的测试循环来用 a 填充 351k 值range(),它会起作用。我怀疑该数组导致内存碎片,然后内存不足。
在 Java 中,我可以使用ArrayList al = new ArrayList(351000);.
我看到array_fill了,array_pad但是那些将数组初始化为特定值。
我使用了答案的组合。凯文的答案单独有效,但我希望随着规模的增长,也能防止未来出现问题。
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;
Run Code Online (Sandbox Code Playgroud)
PHP 有一个带有 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';
Run Code Online (Sandbox Code Playgroud)
给出
0 => 测试1
1 => 测试2
2 => 测试3