Inside loop structures excessive memory usage can lead to problems, especially if this usage keeps growing after each loop iteration.
If you want to make sure a loop isn’t using too much memory, it’s a good idea to profile it.
How can you do it?
To begin with, you should print the memory usage before and after the loop to check the difference.
If you see that the memory usage is too high, then you should also check inside the loop itself.
The $real_usage parameter is better left to false, because you want to profile your code in detail more than your whole script.
It’s also useful to see how much of the maximum available memory is being used.
A PHP script can use only up to a certain amount of memory. This value is set in the memory_limit variable of the php.ini file (the main PHP configuration file).
You can retrieve that value with the ini_get() function, convert it into bytes and compare it to the script’s memory usage.
Here’s an example: