PHP: The cost of a million objects on function calls

Especially, if you are a start-up, all it takes is a fine combination of:

  • a bad coder (with an arrogant attitude of “code first + optimize later”)
  • and 1000 simultaneous requests

to bring each of your servers to its “knees”.

On part 1, I’ve mentioned the cost of a million items when we are using arrays in PHP.

In this part, I want to highlight related features when we are passing such arrays to functions.

  • version 1: array of arrays: passed by value
  • version 2: array of arrays: passed by reference
  • version 3a: array of objects: passed by value and reassigned objects in function
  • version 3b: array of objects: passed by value without reassigned objects
  • version 4: array of objects: passed by reference

Let’s see the first version of the code:

I’ve got the best results when I used the version 4:

You can see all the files on my github project.

The surprising cases for me were version 3a and version 3b. Simply, I didn’t expect a difference of 50MB because I thought they are effectively doing the same job.

And here is the chart to compare them:

php-memory-usage-chart-on-function-calls

Note: This time, I didn’t use the logarithmic scale.

Leave a Comment