xenador
xenador

Reputation: 211

php < 5.3 garbage collection, do array values need to be set null or does setting the array = null orphan all its elements?

so I am using php 5.2 and needing some garbage collection since I am dealing with very limited resources and large data sets.

from my tests I have seen that unset does nothing until the end of the script(even if I run out of memory), which seems a little bit contrary to the documentation, although I assume that I am also reading the 5.3 docs not the 5.2 docs and the 5.3 docs seem relatively undocumented.

An barebones sample of my class is as follows:

class foo{
private $_var;

public function __construct(){
  $this->_var = array();
  for($i = 0; $i < 10000000000; $i++){
       $this->_var[rand(1, 100000)] = 'I am string '.$i.' in the array';
  }
}

  public function myGC(){
    $this->_var = null;
  }
}

in my function 'myGC()' should I do a foreach over the array and set each element I encounter to NULL (as I remember doing in C++) or would setting $this->_var = NULL free not only the pointer to the array but also all elements associated with the pointer?

Upvotes: 1

Views: 7042

Answers (2)

johndodo
johndodo

Reputation: 18271

You don't call myGC() anywhere, is this the problem?

To test the assumption about unset not working, try running the below example. If it fails, your assumption is correct. If not - you have some other error.

class foo{
    private $_var;

    public function __construct(){
      $this->_var = array();
      for($i = 0; $i < 10000000000; $i++){
           $this->_var[$i] = 'I am string '.$i.' in the array';
           unset($this->_var[$i]);
      }
    }
}
$f=new foo();

Upvotes: 0

powtac
powtac

Reputation: 41050

It's enough to set $this->_var = NULL, this frees the memory for everything $this->_var was set to.

You can test it with this (pseudo code)

echo 'before: '.memory_get_usage().'</br>';
$Test = foo();
echo 'after class instance: '.memory_get_usage().'</br>';
$Test = foo->myGC();
echo 'after unset of _var: '.memory_get_usage().'</br>';
$Test = NULL;
echo 'after unset of object: '.memory_get_usage().'</br>';

Upvotes: 4

Related Questions