PHP Functions - Memory Get Usage and Memory Get Peak Usage
If your code is using a lot of memory you can check it with the php function memory_get_usage. This function returns the amount of memory used by the script (in bytes). There is another php function called memory_get_peak_usage which returns the maximum amount of memory used by the script. Both functions take a boolean argument $real_usage. This should be set to true if you want to see the actual memory used by the PHP engine, not just the memory allocated by your code. By default it is false.
When the value of $real_usage is true both function return all memory used by the php engine, including unused pages. This can be useful to see how much memory the zend engine itself is using, or if there is an issue with external libraries such as libxml which may be consuming large amounts of memory.
A common issue is creating a loop which iterates over an array, such as foreach(). This will consume a lot of memory because of copy-on-write. This means that each time the loop iterates over an element, a full copy of the array is created and then added to the variable pointing to it. The result is that the variable's refcount is incremented - but this is a waste of memory because it doesn't change anything in the loop!
Unless you are very careful it is easy to use up your hosting provider's available RAM this way. In the next article I'll show how to avoid this by properly unsetting variables when they are no longer needed - and by letting PHP garbage collect en masse at the end of your script.