Debugging memory usage

Last week, an issue was reported for a site. It only occurred sometimes and the result was an Error 500. Activating the WP_DEBUG mode I was quickly able to find out that the memory limit was hit. The only fix was an increase of this limit, as the functionality on the pages used quite a lot memory and an optimization was not easy to find.

In those cases it would be nice to be able to find out how much you have to increase the limit. So how much would a page load usually take. There are several ways to find this out.

The danegerous way

One simple solution would be to decrease the memory limit until you always get a memory limit error. Then you slightly increase the limit until you only get the error some times. This is the value the actual usage would likely be. Then you add some more to that limit, so you don’t run into it again.

Obviously this approach is not really ideal! If you do this on a live website (which might consume different amount of memory than you local development system), you intentional break a live site. You might be OK doing this for some few minutes in a low traffic time, but there are better ways to get the limit.

Use the “Query Monitor” plugin

For any debugging purpose I usually always check the Query Monitor plugin first, as it has lots of debugging information. Fortunately the memory usage is one of them. You will find it in the “Overview”:

Query Monitor Overview

This will show you the “Peak Memory Usage” and how much of the set memory limit that is. So in cases where you get an Error 500 an a specific page, increase the memory limit so you can check the actual usage with Query Monitor and then set a good new value.

Write your own helper plugin

Query Monitor is using a core PHP function to get those numbers. You might want to take a look at memory_get_usage() and memory_get_peak_usage() for your own little helper plugin. This is especially helpful if you try to debug pages where Query Monitor cannot be used or when trying to find memory limit of AJAX/REST calls and such.

Conclusion

Finding memory limit errors is sometimes a bit tricky. But with the help of the Query Monitor plugin or some core PHP functions it’s a rather easy task. The harder task is to find a way to make your website need less memory. I’ve seen issues particularly with some heavy page builder who sometimes requite more than 512 MB in the backend!

Posted by

Bernhard is a full time web developer who likes to write WordPress plugins in his free time and is an active member of the WP Meetups in Berlin and Potsdam.

Leave a Reply

Your email address will not be published. Required fields are marked *