DEV Community

Cover image for Greedy Arrays in PHP
Edmond
Edmond

Posted on

Greedy Arrays in PHP

In some optimized PHP applications, you may occasionally see “strange code” like $this->array = [] after heavy usage. There’s an array that held many elements, and then it suddenly gets cleared by assigning a new empty array. You might think, “that’s just how the author wrote it.” But most likely not — the author is probably familiar with the problem of greedy arrays in PHP.

The idea: PHP arrays can grow dynamically, but they do not shrink dynamically.

Example. Suppose you created a queue of 10,000 elements. You processed everything. But in reality, the memory remains allocated. Is this a problem? Yes. If you’re writing stateful applications, this can become an issue. Nothing seems wrong, yet your process keeps growing over time, and you can’t even figure out why. Sound familiar? Here’s the culprit.

That’s why for long-running PHP applications it’s recommended to always explicitly clear large arrays.

The operation $this->array = [] tells the PHP engine to fully release the entire memory block, after which the object property is assigned a constant empty array.

Why is it designed this way? Because automatic shrinking of data structures is one of the most complex algorithms. It either complicates the code significantly or leads to performance loss. So the decision in PHP is reasonable: do not shrink arrays automatically. However, this still remains a language limitation. How to solve it? Possibly by introducing a new garbage collector.

Top comments (0)