gpt4 book ai didi

php - 如何在 PHP 中为数组预分配内存?

转载 作者:行者123 更新时间:2023-12-05 08:43:14 24 4
gpt4 key购买 nike

如何在 PHP 中为数组预分配内存?我想为 351k 多头预分配空间。该函数在我不使用数组时有效,但如果我尝试在数组中保存长值,则它会失败。如果我尝试一个简单的测试循环来用 range() 填充 351k 值,它就可以工作。我怀疑是数组造成了内存碎片,然后内存不足。

在 Java 中,我可以使用 ArrayList al = new ArrayList(351000); .

我看到了array_fillarray_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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com