诊断内存泄漏-允许的内存大小已耗尽#个字节 [英] Diagnosing Memory Leaks - Allowed memory size of # bytes exhausted
问题描述
我遇到了可怕的错误消息,可能是经过艰苦的努力,PHP内存不足:
I've encountered the dreaded error-message, possibly through-painstaking effort, PHP has run out of memory:
在第123行的file.php中允许的####个字节的内存大小用尽(试图分配####个字节)
Allowed memory size of #### bytes exhausted (tried to allocate #### bytes) in file.php on line 123
提高限额
如果您知道自己在做什么并且想要增加限制,请参见当心!您可能只是在解决症状,而没有解决问题!
Beware! You may only be solving the symptom and not the problem!
错误消息指向带有循环的一行,我认为这是正在泄漏或不必要地累积内存.我在每次迭代结束时都打印了memory_get_usage()
语句,可以看到该数字缓慢增长直到达到极限:
The error message points to a line withing a loop that I believe to be leaking, or needlessly-accumulating, memory. I've printed memory_get_usage()
statements at the end of each iteration and can see the number slowly grow until it reaches the limit:
foreach ($users as $user) {
$task = new Task;
$task->run($user);
unset($task); // Free the variable in an attempt to recover memory
print memory_get_usage(true); // increases over time
}
出于这个问题的目的,我们假设可想象的最糟糕的意大利面条代码隐藏在$user
或Task
中的global-scope中.
For the purposes of this question let's assume the worst spaghetti code imaginable is hiding in global-scope somewhere in $user
or Task
.
哪些工具,PHP技巧或调试伏都教可以帮助我发现并解决问题?
推荐答案
PHP没有垃圾收集器.它使用引用计数来管理内存.因此,内存泄漏的最常见来源是循环引用和全局变量.恐怕,如果使用框架,您将需要大量代码来查找它.最简单的工具是有选择地对memory_get_usage
进行调用,并将其范围缩小到代码泄漏的位置.您还可以使用 xdebug 创建代码跟踪.使用执行跟踪和show_mem_delta
.
PHP doesn't have a garbage collector. It uses reference counting to manage memory. Thus, the most common source of memory leaks are cyclic references and global variables. If you use a framework, you'll have a lot of code to trawl through to find it, I'm afraid. The simplest instrument is to selectively place calls to memory_get_usage
and narrow it down to where the code leaks. You can also use xdebug to create a trace of the code. Run the code with execution traces and show_mem_delta
.
这篇关于诊断内存泄漏-允许的内存大小已耗尽#个字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!