0

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.

2
  • 4
    You might want to check out memory_limit here: php.net/manual/en/ini.core.php Commented Mar 7, 2017 at 11:29
  • @sensorario you can follow some standard guidelines. 1. Don't use un-used variable. 2. If possible, just unset the variable right after using that if you don't need that again for that execution. Also remember, it depends on your logics, structures and codes you are working on. In google, you can have some stuff about to optimize PHP memory. Commented Mar 7, 2017 at 11:30

2 Answers 2

1

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 e.g.:

$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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.