【发布时间】:2015-12-05 12:42:34
【问题描述】:
如何在 PHP 中为数组预先分配内存?我想为 351k longs 预先分配空间。该函数在我不使用数组时有效,但如果我尝试在数组中保存长值,那么它会失败。如果我尝试一个简单的测试循环来用range() 填充 351k 值,它就可以工作。我怀疑该数组导致内存碎片,然后内存不足。
在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;
【问题讨论】:
-
“当我不使用数组时”和“然后它失败”是什么意思?发生什么了?您是否看到任何错误消息?
-
您是否有不想将数组元素初始化为特定值的原因?
-
“当我不使用数组时,该函数有效” - 我们可以看到函数的代码吗?
-
你想通过预分配内存来解决什么问题?如果您因致命错误而内存不足,那么 Kevin 下面提出的解决方案就是您问题的答案。确定存储
Nlongs 数组需要多少内存,添加您可能需要的任何额外内存,然后将脚本的memory_limit设置为足够大的值。
标签: php arrays memory-management