为什么 debug_backtrace() 使用这么多内存? [英] Why is debug_backtrace() using so much memory?

查看:61
本文介绍了为什么 debug_backtrace() 使用这么多内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试跟踪 PHP 中的某些内存问题时,我注意到我在日志记录代码中调用的 debug_backtrace() 似乎使用了大量内存.

When trying to trace some memory issues in PHP, I noticed that debug_backtrace(), which I call in my logging code, seemed to be using a lot of memory.

在大多数情况下,以下代码会打印类似 0.02 MB 的内容.但在一种情况下,它会打印 171.85 MB!

In most cases, the following code prints something like 0.02 MB. But in one case, it prints 171.85 MB!

$before = memory_get_usage();
$backtrace = debug_backtrace(false);
$after = memory_get_usage();
echo round(($after - $before)/1024/1024, 2)." MB";

我的问题是,这是否意味着 debug_backtrace 实际上使用了那么多内存?或者可能发生了其他事情,例如垃圾收集,从而弄乱了 memory_get_usage 的返回值?

My question is, does this mean that debug_backtrace is actually using that much memory? Or could something else be happening, like garbage collection, that messes up the return value from memory_get_usage?

推荐答案

好吧,我想我明白了.我打印了回溯,"args" 数组很大.这是因为我正在传递一些巨大的字符串.我猜它在返回结果时复制了它们(而不是引用).

Okay, I think I figured it out. I printed out the backtrace, and the "args" array was huge. This is because I was passing around some enormous strings. I guess it's making copies of them (instead of references) when returning the results.

例如:

function test($str) {
    test2($str);
}
function test2($str) {
    test3($str);
}
function test3($str) {
    echo "before: ".round(memory_get_usage()/1024/1024, 2)." MB\n";
    debug_backtrace(false);
    echo "after: ".round(memory_get_usage()/1024/1024, 2)." MB\n";
}
test(str_repeat('a', 10000000));

在有和没有 debug_backtrace() 调用的情况下试试这个.有了它,内存使用量增加了大约 28 MB.只有在 test3() 返回时才会被清除.

Try this with and without the debug_backtrace() call. With it, the memory usage is increased by about 28 MB. It's only cleared when test3() returns.

这篇关于为什么 debug_backtrace() 使用这么多内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆