1

I have read several times that, in order to invoke the garbage collector and actually clean the RAM used by a variable, you have to assign a new value (e.g. NULL) instead of simply unset() it.

This code, however, shows that the memory allocated for the array $a is not cleaned after the NULL assignment.

function build_array()
{
 for ($i=0;$i<10000;$i++){
    $a[$i]=$i;
 }
 $i=null;
 return $a;
}

echo '<p>'.memory_get_usage(true);

$a = build_array();

echo '<p>'.memory_get_usage(true);

$a = null;

echo '<p>'.memory_get_usage(true);

The output I get is:

262144

1835008

786432

So part of the memory is cleaned, but not all the memory. How can I completely clean the RAM?

Eugenio
  • 3,195
  • 5
  • 33
  • 49

2 Answers2

4

You have no way to definitely clear a variable from the memory with PHP.

Its is up to PHP garbage collector to do that when it sees that it should.

Fortunately, PHP garbage collector may not be perfect but it is one of the best features of PHP. If you do things as per the PHP documentation there's no reasons to have problems.

If you have a realistic scenario where it may be a problem, post the scenario here or report it to PHP core team.

Other unset() is the best way to clear vars.

pipblip
  • 61
  • 3
  • Thanks, so basically the fact that assigning a value clean the memory in use, as I've read several times (e.g. here http://v1.srcnix.com/2010/02/10/7-tips-to-prevent-php-running-out-of-memory/) is not correct? – Eugenio Mar 09 '16 at 16:51
0

Point is that memory_get_usage(true) shows the memory allocated to your PHP process, not the amount actually in use. System could free unused part once it is required somewhere. More details on memory_get_usage could be found there

If you run that with memory_get_usage(false), you will see that array was actually gc'd. example

Community
  • 1
  • 1
Evgeny Soynov
  • 704
  • 3
  • 13
  • Yes, but finally the memory allocated is the important value I guess when it comes to avoid max memory allocation errors in PHP. – Eugenio Mar 09 '16 at 16:51