PHP Memory Usage: The cost of a million objects

Even though memory is getting cheaper, our applications are becoming more complicated and we need to write our code more carefully. I’d like to share some surprising tests I’ve written recently. The sample code files are also on github: https://github.com/muratyaman/php-tips.

The tests are very simple: let’s create an array of million items to process:

  • version 1 includes an array of arrays
  • version 2 includes an array of objects using stdClass
  • version 3 includes an array of a custom class using magic methods for attributes
  • version 4 includes an array of a custom class using public attributes (private did not make a difference)

Here is the first version:

Output of v1 is:

Likewise, if you follow the versions on github, version 4 has the best results. The code is:

Output v4 is:

What surprised me is that PHP is managing the memory more efficiently when we define simple classes and create objects based on them. It is almost 1/3 of the usage when we have a million objects using a custom class with magic methods for attributes. On the other hand, resetting an array of arrays (and running GC) gives almost all the memory back to the system. Main lesson for me is that magic methods are evil.

NOTE: a useful function to mention is gc_collect_cycles() which enables us to run garbage collection on demand. In my case (Windows 7, PHP 5.6.12) it helped me reduce memory usage i.e. we can run it after setting our array to null (when we finish using it, and we want to continue with some other long process).

Here is a quick snapshot of the chart to compare the results:
php-memory-usage-chart

Leave a Comment