PHP stack trace

Tracking down an error in PHP code often requires knowledge about how the function is being called.  In cases such as this a stack trace is often useful to show the call stack.  PHP has a function debug_backtrace() that I have found useful in displaying the call stack.  But it seems to use a lot of resources.  So I wanted to quantify this and try a new approach that I have been using lately.  I used something in Drupal 8 that I was debugging.  Results will differ greatly depending on the case but the overall trends should be similar.  I used

var_dump(memory_get_usage());

Running the code with just this statement resulted in 7.56 MB of memory used. Then I added just before this statement the statement

kint(debug_backtrace();

kint() is part of the Devel project. The memory usage jumped to 21.96 MB. Then I replaced this with

$e = new \Exception;
kint($e->getTraceAsString());

The memory usage for this approach is 7.70 MB. The output is also simpler and easier to read although debug_backtrace()provides much more information about the arguments being passed.

 

Categories