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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With