Published 4 weeks ago by asaketr64x
I have heard about memory leaks but never faced one.I want to know what things can cause a memory leak in a LARAVEL PROJECT .Is it too much of sql queries or long process time or what?. Thanks for the suggestions. Also what practices should I follow to avoid it?
A memory leak is a specific type of problem where something is put in memory but never removed. This is much less a problem for a HTTP request as when the request is complete the process goes away so even if you have a memory leak it likely wont matter much. They are much more problematic for a long running process or a cli script.
Php is pretty good at garbage collection so memory leaks aren't too common but they do happen from time to time.
Generally where you need to watch out for them is in loops. To avoid memory leaks in your scripts you really just need to close any open file streams, destroy image resources, or close any open socket connections when you no longer need them. Also if you have a variable that takes up a large amount of memory you might want to unset it yourself one you don't need it anymore rather than wait for the garbage collector to do it for you.
The other thing you might need to watch out for is cyclic references.
Overall this isn't something you should be too worries about. I've probably only had one cause an issue a dozen times or so in the 12+ years I've been programming in php.
One thing laravel does is track all queries that are run in memory for each request cycle. For regular pages, this isn't a big deal, but if you are running a long process that is making thousands of queries, it could overrun the memory. Like I have a process that takes several hours pulling down real estate listings from various api's, and parsing the results and inserting the records into the db, which results in hundreds of thousands of queries. It would run fine for about 30 minutes or so until it overran the memory (512M). The only fix I've found for it is:
and then it would run for hours and the entire process consumed no more than 6M, and it was a lot faster as well. So, I just put that before any long running process and it's been fine.
@avaneeshsingh Interestingly enough, it's mentioned in older docs, but not for more recent versions: https://laravel.com/docs/5.0/database#query-logging. It looks like it was removed from the docs for v5.1 and up.