PHP 尝试分配不必要的内存(数百 MB 可用内存,分配的内存超过允许的内存,抛出'Allowed memory size'错误)(PHP7)



我有一个从cron任务运行的PHP脚本。我不是这样的

<?php
require_once 'script1.php';
// Here I do a lot of SQL querys, and my memory usage and allocated memory goes up
// then I set all the variables to null and unset them to free memory
gc_collect_cycles(); // I added this to try to force freeing memory
require_once 'script2.php';
// Here I do a lot of SQL querys, and my allocated memory goes up again ...
gc_collect_cycles(); // I added this to try to force freeing memory
require_once 'script3.php';
// And Here when I do one big query it throws me the 'Allowed memory size' error.

这些是内存的转储,用..

MEM=memory_get_usage(false)
MEMR=memory_get_usage(true)
MEMpeak=memory_get_peak_usage(false)
MEMRpeak=memory_get_peak_usage(true)

1) 在脚本 1 之后:

MEM 5.9628219604492 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 248.5

2) 脚本 2 之后:

MEM 7.9203491210938 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 251.34765625`

3) 在脚本 3 之前:

MEM 7.8667755126953 MEMR 244 MEMpeak 243.41315460205 MEMRpeak 251.34765625

4)在脚本3上,我做"mysqli_query(...")之前的那行:

MEM 9.0010223388672 MEMR 244 MEMpeak 243.419090271 MEMRpeak 251.34765625

然后我得到错误: PHP 致命错误:Allowed memory size of 268435456 bytes exhausted (tried to allocate 19552176 bytes) in ...

但是,如果我将内存限制增加到 512M,我会在之前崩溃的行之后得到这个内存转储:

MEM 35.54125213623 MEMR 266.6484375 MEMpeak 243.419090271 MEMRpeak 266.6484375

我不明白发生了什么:在乞求脚本 3 时,我有 243MB 的已分配内存和 9MB 的已用内存(所以我仍然有 234 MB 的可用分配内存,对吧?

然后 PHP 尝试再分配 22MB 的内存(必须在内存上再保存 29MB 的数据)。

为什么不使用可用分配的内存?

编辑:当我单独运行脚本3时,这些是我的读数:

  • 开始:

    MEM 5.83447265625 MEMR 8 MEMpeak 6.7176361083984 MEMRpeak 8

  • 结束(将所有变量设置为 NULL 之前):

    MEM 57.858413696289 MEMR 90.25 MEMpeak 107.6799621582 MEMRpeak 108.8984375

  • 结束(将所有变量设置为 null 后):

    MEM 6.9840774536133 MEMR 88 MEMpeak 107.6799621582 MEMRpeak 108.8984375

尝试在 fetch all 的 insead 中逐行使用 fetch

最新更新