Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is debug_backtrace() using so much memory?

Tags:

php

memory

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.

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";

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?

like image 359
JW. Avatar asked Dec 13 '22 15:12

JW.


1 Answers

Its the objects, most likely, that are causing the bloat. Try passing false to the function so you don't pull the objects and your traces will be much smaller.

EDIT: If passing false doesn't work then if you're running PHP 5.3.6+ you can use a bitmask to limit what the function returns. What it sounds like is that you have objects being passed as args that are huge.

http://php.net/manual/en/function.debug-backtrace.php Reference

Additionally if you are using PHP 5.4.0+ they added a second param that will allow you to limit the number of stack frames.

EDIT2: total <<HACK>> here, but works ... add a try/catch, throw an exception and catch it then convert to string or call exception getTraceAsString() to get the full stack. Example:

try {
    throw new Exception('ignore this string');
} catch(Exception $e) {
    /* @var $trace array */
    $trace = $e->getTrace();

    // OR

    /* @var $str string */
    $str = $e->getTraceAsString();
    $e = null;
}

In the above snipped you can use $trace and build your own output or just use the standard exception as string $str. Easier to get the stack frame output.

like image 186
Yzmir Ramirez Avatar answered Dec 26 '22 17:12

Yzmir Ramirez