php < 5.3 garbage collection, do array values n

2019-02-20 16:31发布

问题:

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?

回答1:

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>';


回答2:

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();