Php尝试分配不必要的内存(数百MB空闲,分配超过允许的数量,抛出“允许的内存大小'错误”)(PHP7)

时间:2017-05-25 11:09:20

标签: php memory memory-management memory-leaks php-7

我有一个从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上,在我做一个&#39; mysqli_query之前的那一行(......&#39;:

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

1 个答案:

答案 0 :(得分:0)

尝试逐行获取fetch all的行。