我有一个 16 MB 大小的 CSV 文件并尝试解析它,并做一些事情,但一段时间后脚本内存不足。我意识到这段代码生成了大约 200 MB 的已用空间并且 unset 不起作用。
$countRows = 1;
var_dump("3. ".memory_get_usage()." beginDiff: ".(memory_get_usage() - $this->startingMemory));
while(($row = fgetcsv($fp, 300000, ';', '"')) !== FALSE)
{
if ($row == '')
continue;
if($firstRow == true)
{
foreach($row as $k => $v)
{
$this->columnMapping[$k] = trim(mb_strtolower($v));
}
$firstRow = false;
continue;
}else
{
foreach($row as $k => $v)
{
$row[$this->columnMapping[$k]] = $v;
unset($row[$k]);
}
}
...
//$this->theirCategoriesToProducts[$row['kategorie']][]['kodproduktu'] = $row['kodproduktu'];
$this->theirCategoriesToProducts[$row['kategorie']][] = $row;
}
var_dump("3,5. ".memory_get_usage()." beginDiff: ".(memory_get_usage() - $this->startingMemory));
...
var_dump("7. - before unset total: ".memory_get_usage()." beginDiff: ".(memory_get_usage() - $this->startingMemory));
unset($this->theirCategoriesToProducts);
var_dump("8. - after unset total: ".memory_get_usage()." beginDiff: ".(memory_get_usage() - $this->startingMemory));die;
生成此输出:
string '3. 72417440 beginDiff: 34730040' (length=31)
string '3,5. 292748528 beginDiff: 255061136' (length=36)
string '7. - before unset total: 299039360 beginDiff: 261351984' (length=55)
string '8. - after unset total: 297364432 beginDiff: 259677056' (length=54)
设置该变量等于 null 的输出非常相似。但是在这两行之间切换注释
$this->theirCategoriesToProducts[$row['kategorie']][]['kodproduktu'] = $row['kodproduktu'];
//$this->theirCategoriesToProducts[$row['kategorie']][] = $row;
将输出:
string '3. 72417784 beginDiff: 34730040' (length=31)
string '3,5. 81081984 beginDiff: 43394248' (length=34)
string '7. - before unset total: 87256544 beginDiff: 49568824' (length=53)
string '8. - after unset total: 85581520 beginDiff: 47893800' (length=52)
所以它大约有 200 MB 的“丢失”内存(几乎是专用内存的一半)。
取消设置数组所有部分的递归函数会消耗更多的内存,而不是能够释放所以也崩溃了。
在脚本中永远不会使用带有 & 的数组,因此不应该引用其他变量。
文件在 3.5 转储后立即关闭。
任何其他想法,如何取消设置该数组?