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

标签 php arrays memory-management

如何在 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/

相关文章:

php - HTTP header 阻止浏览器加载页面?

java - 如何从 Java 中的组合框中删除特定项目?

java - 求部分填充数组的平均值

.net - 循环内的变量声明

php - 在 UserSpice 中格式化时间戳

php - 缓存和调整图像大小而不缩小或拉伸(stretch)?

arrays - 如何在R中制作和排序元组数组

r - 将文档术语矩阵转换为包含大量数据的矩阵会导致溢出

c - 静态变量的地址相同,但局部变量的地址不同

php - 奇怪的字符编码问题导致js函数失败或添加不需要的字符