How to Prevent Your PHP Script Running Out of Memory

There is good chance you are familiar with this error.

What’s the cause of this error. How you prevent your PHP script running out of memory. Let’s talk about it. In any programming language memory is cleared up by the garbage collector. And garbage collector does this work perfectly. For clearing up the memory, you need to tell the garbage collector that the following allocated memory is ready to free. In PHP this can be done by calling unset().

Unset() –  unset the variable.

Simple example.

output – hello

Is unset() free memory

unset() only unset the variable, and tells the garbage collector that variable is no longer live you can free that memory. Until the garbage collector doesn’t free the memory, the memory occupied by the variable still remains. The garbage collector of any programming language works very smartly and usually you don’t have to take care of how it works.

Subscribe Our Tutorials

Get Latest Updates on Facebook

In few cases, garbage collector doesn’t free the memory on time and in that case if you’r script takes memory then you get the fatal error.

Fatal error: memory size exhausted.

Other way to free memory is to assign null to your variable and then unset. In that case you are rewriting the data, which free memory faster.

Increase memory limit

use memory_get_usage() function

If you want to know how much memory your script consume you can use memory_get_usage() function. It will tell you how much memory your script are using. This is good if you want to know which part of your script taking memory.

You can share you views and other tips which helps to prevent memory exhaust error.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.
Tagged , , . Bookmark the permalink.