Laravel: Fixing memory leaks on tests

And… well, any CLI operation on Windows

Manual ol’ classic bug hunting

Believe it or not, one of the common memory leaks are static properties. On classic requests, PHP executes and destroys itself, so these not pose a problem because everything is thrown out of the window for the next request.

Cleaning your room

In a nutshell, a destructor on Test Classes are never called because there is a reference somewhere (probably inside PHPUnit itself) even after the Test Class completes. Practically, the reference is deleted once there are no more test to run, which is when PHPUnit exits.

Shoving the vacuum cleaner

If you’re really lazy, or you have a lot properties defined and you can’t track all of them everywhere, you may want to use this code based on one found in StackOverflow.

Pushing the Container to the endless pit

Sometimes PHP may keep a Laravel application instance around in memory because of yes. It’s very rate, but some folks say it sometimes happen.

Taking the garbage out

You shouldn’t need to call the Garbage Collector on PHP, but you can anyway with gc_collect_cycles(). This functions calls the Garbage Collector which immediately frees up the memory of any lingering variable pointing to null or unset.

Buy four trucks, or eight

Having many test cases with such memory leaks make the whole testing slower as it progresses. Luckly, Laravel is compatible with Paratest. In other words, multiple PHPUnit processes will spawn for each Test Class, that will be executed in parallel.

Buy a house while you’re at it

If you can’t find the memory leak, but you’re urged to get the test rolling anyway in a single process, let me introduce you to raising the memory limit.

PS> php -dmemory_limit=1024M ./vendor/phpunit/phpunit/phpunit

OPcache to the rescue!?

This one was weird, but I found it nonetheless. Let’s start with how OPcache describes itself:

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.