At work, I’ve been trying to solve an out of memory error we’ve been seeing in a long running validation process. It typically takes about 6 hours to complete but over the New Year’s holiday, it started notifying us of the out-of-memory errors. The trouble appeared to involve our repeated use of the switch_to_blog()
method so I started looking into possible ways to optimize this script and hopefully eliminate the errors.
The validator takes a large list of blog_ids and switches each one to check on WooCommerce order data. If you’re not familiar with switch_to_blog()
it essentially changes the currently used site in a WordPress network installation so data can be queried from it as if it’s the site loaded.
The recommended way to apply this method is to run it, perform any actions you need, and then use the restore_current_blog()
method to return to the “normal” site ID for that situation. If the original blog ID isn’t restored, it can result in incorrect URLs being given to site visitors.
Our script is run via a CLI command so we’re not dealing with URLs for visitors in this context. That made me wonder if we really needed to restore the original blog during each loop. If we could eliminate that, it would remove half of the switch_to_blog()
calls!
So what I tried was setting a variable with the current blog id using get_current_blog_id()
and removing the restore_current_blog()
method from each iteration of the loop. Then at the end, I restored the original blog ID this way:
switch_to_blog( $this->first_blog_id );
$GLOBALS['_wp_switched_stack'] = array();
$GLOBALS['switched'] = false;
When I ran the validator with this code in place, it was 4 hours (40%) faster! Plus we didn’t run into any out-of-memory errors. So if you find yourself in a situation where you’re calling switch_to_blog()
many times and you’re not serving content to visitors as part of the request, look into skipping restore_current_blog()
and see if it’ll speed up your application.
Leave a Reply