Prevent Memory Leak in WordPress

Recently I faced an issue of memory leak in one of my WordPress projects. I was running a function that was reading post meta and user metadata of thousands of objects. I thought reading data from MySQL is cheap in terms of processing power and memory, but it turned out it was causing my function to crash giving an out-of-memory error.

I made sure that there was no update being done to either post meta or user meta. It was only reading data through get_user_meta() and get_post_meta() functions. Then what was the reason for the memory leak?

It turned out that WordPress caches all the results when we read or write to post and user meta. That’s why, on iterating through thousands of posts and users, the result of each was being cached in memory, thus resulting in out-of-memory error.

To fix this issue, we need to prevent WordPress from caching this data. This can be done through wp_suspend_cache_addition(). This function disables the cache addition for the current page execution. This is how we need to call this function at the start of our script.

wp_suspend_cache_addition( true );

And that’s it. Memory usage dropped to less than 6 MB with peak memory usage coming down to mere 13 MB.

If you are facing a similar issue in WordPress, do remember this function. Also, while writing cron scripts or scripts to bulk update data like import/export scripts, it is better to call this function to ensure there is no out-of-memory issue.

Share this:

Leave a Comment

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