作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 PHP 中为数组预分配内存?我想为 351k 多头预分配空间。该函数在我不使用数组时有效,但如果我尝试在数组中保存长值,则它会失败。如果我尝试一个简单的测试循环来用 range()
填充 351k 值,它就可以工作。我怀疑是数组造成了内存碎片,然后内存不足。
在 Java 中,我可以使用 ArrayList al = new ArrayList(351000);
.
我看到了array_fill
和 array_pad
但是那些将数组初始化为特定值。
我使用了答案的组合。凯文的回答单独起作用,但我希望随着规模的增长也能防止 future 出现问题。
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;
最佳答案
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';
给予
0 => test1
1 => test2
2 => test3
关于php - 如何在 PHP 中为数组预分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32481362/
我是一名优秀的程序员,十分优秀!