简体   繁体   中英

How much memory has a php script? Can I free memory during execution?

Can php script get allowed memory size and also how much memory can be allocated? I know that it is possible to clean memory using unset . But I'll like to understand how to create php scripts that consume less memory as possibile.

The basic mechanism which PHP uses is garbage collection

How it works in short is something like:

Say you have a certain memory location M allocated to store variable $m eg:

$m = [ 0,1,2,3,4,5 ]; //M refers to the memory which is storing this array

As long as $m keeps pointing to M then PHP is not allowed to destroy M. However if you do something like:

$m = null;

This makes $m point to nothing and therefore M no longer is referenced by anything. PHP at this point is allowed to clear that memory, but may not do so immediately. The point is if you ensure that you stop referencing something when you don't need it anymore you're giving PHP the opportunity to run as memory optimized as possible.

However, garbage collection for large complex applications is expensive so keep in mind that PHP may opt to delay garbage collection if it can.

unset will free the memory.

Though major memory consumption will be on the resources from io, db etc.

And for these tasks, it is very important to release the memory or free up the sources for further utilisation.

Also to note that while processing, the processed data will also have near similar usage. Hence freeing that after usage will also improve the use case.

To go more and more memory less, make functions pure as much as possible, where after execution of function, there is only output and no side effect. With this there will be less things in global memory space.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM