How to recover from a fatal error “Allowed memory size exhausted”

前端 未结 7 968
梦如初夏
梦如初夏 2021-01-04 08:52

Do you know any solution to recover from the PHP fatal error : \"Allowed memory size ... exhausted\"

I have a shutdown function that is called when a fatal

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-04 09:21

    if((memory_get_usage() / 1024 /1024) < 70)
    

    I simply divide the memory_get_usage by 1024 squared to compare it to a 'normal' megabyte value of '70'.

    I ran into memory problems with php inside a for loop and wrote this simple if statement to prevent my script from setting off a fatal error. In addition, the server I was operating on didn't allow me to modify the memory limit (this is often the case in some cloud offerings like openshift or large web hosts like dreamhost.) I didn't really notice any serious performance degradations (in php 5.3 which may handles functions such as this slightly differently than php 4.x or 5.x... at any rate the performance implication of a script giving a fatal error outweighs any overhead the function call may force. And would also prevent a runaway script from consuming all available ram.

    Many may argue; oh hey your software isn't optimized. Yes. You're probably right; but with complex data sets you can only squeeze so much performance out before you need to throw more memory at it; and hunting down memory errors in an ajax flow can be very frustrating; especially when you aren't sure where your log files are.

提交回复
热议问题