Memory management is not something that most PHP developers ever need to think about. I’m running into an issue where my command line script is running out of memory. It performs multiple iterations over a large array of objects, making multiple database requests per iteration. I’m sure that increasing the memory ceiling may be a short term fix, but I don’t think it’s an appropriate long-term solution. What should I be doing to make sure that my script is not using too much memory, and using memory efficiently?
Memory management is not something that most PHP developers ever need to think about.
Share
The golden rule
The number one thing to do when you encounter (or expect to encounter) memory pressure is: do not read massive amounts of data in memory at once if you intend to process them sequentially.
Examples:
file); instead, read one line at a timeThis is not always the most convenient thing in PHP (arrays don’t cut it, and there is a lot of code that only works on arrays), but in recent versions and especially after the introduction of generators it’s easier than ever to stream your data instead of chunking it.
Following this practice religiously will “automatically” take care of other things for you as well:
Other things to do