While running a PHP script you may encounter the dreaded “Fatal error: Out of memory” message. It is usually be accompanied with a few long numbers which represent the number of bytes the script tried to allocate.
The obvious fix would be to increase the memory limit in the php.ini, apache config, .htaccess or at the top of the script itself:
ini_set('memory_limit', '64M');
Increasing the amount of memory will possibly make the error disappear, but for how long? Really all you are doing is suppressing the problem, which will more than likely rear it’s ugly head again in the future.
The best course of action is to get to the real root cause of the problem. Why is the script using so much memory? Can the code be refactored to make it more efficient?
In order to diagnose why, you need to identify where. Some strategically placed debug code is required. Using memory_get_usage(), a built in PHP function, will return the number of bytes the script is using at that point.
echo memory_get_usage(); // Make it more human-readable. Convert Bytes to MB. echo intval((memory_get_usage() / 1024) / 1024) . "MB\n";
It can be a little tedious, but working line by line or in areas you think could be symptomatic will quickly highlight where you should concentrate your optimisation efforts.
A common cause is a very large result set from a MySQL query. The returned data is read into memory and stored until such time PHP decides it’s no longer required. Do you really need to select all fields, or all rows?
SELECT * FROM `tablename` SELECT `id`,`surname`,`age` FROM `tablename`
If you only require 5 of the 10 fields in a table, you consume approximately 50% less memory. On small result sets it’s not significant, but when you have 10K plus rows it can really start to add up. Also consider using LIMIT to only retrieve the rows you need.
There is also a minimal saving to be made by returning the results as an array, rather than an object as can be the case with some Active Record libraries.
The Takeaway
Prevention is better than cure. A quick fix will always come back to byte you!
Continue reading
