Press "Enter" to skip to content

Garbage collection in PHP – Manage and optimize system’s memory

A little demonstration of where things can go wrong.

Write this code and execute it.

Your system should peak up at least 10MB worth of peak memory usage.

That is because we are creating around one hundred thousand variables. And, it is allocating memory in the symbol table of PHP.

Now, while coding you probably won’t do this. But what you will definitely do is this.

Now, that makes things even worse.

Variable $some and couple of other variables like these left around are taking up a small chunk of your memory.

Ever wonder, why sometimes your development environment freezes?

So, a little solution is there.

Now lets add something.

If you execute this code, your peak usage should be around 2-3MB.

So, what is happening here?

Answer: we are creating a new variable in each iteration. PHP has to store it somewhere. So, it is taking up memory. But, this time, we are removing it immediately. So, PHP has no unnecessary variable set in its memory at the end of the iteration. It has only one variable (max) store at any time.

It makes a huge difference.

But this is not how you should be doing things.

Using unset each time is tedious. “You will start nagging about how bad is PHP”.

A better approach.

We can take advantage of garbage collection. PHP performs garbage collection on the request lifecycle.  It has become very efficient, especially in PHP7 and higher and one of the main praise gatherers for PHP.

For example:

Using a function inside an iteration:

or use some array functions like

Using these functions, PHP destroys all the local variable created inside a function. So, memory is freed up immediately and automatically.

Why should we do it?

Each web server can handle the only certain amount of connections at a time. So, if a single request takes up a lot of memory, then fewer users can be served concurrently.

For example: If your server has 1GB RAM allocated for you, and each request is served within 1MB, you can probably handle several hundred concurrent users. (In case of your servers job is only to serve requests)

But, if single user occupies 10 – 20 MB of RAM, you can only server around 50 users at max.

You will quickly need a higher scale of service and cache services like could flare.

So, remember to adhere to some practice. If there are chances of a higher number of iteration, do not set any new variables inside it. Try using functions, array helpers or collections.

As always, Everything is awesome.