php <5.3垃圾收集,数组值是否需要设置为null或者设置array = null orphan其所有元素?
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?
所以我使用php 5.2并需要一些垃圾收集,因为我处理非常有限的资源和大数据集。 p>
从我的测试中我看到unset在脚本结束之前什么都不做(即使我的内存耗尽),这似乎与文档有点相反,尽管我假设 我也在阅读5.3文档而不是5.2文档,而5.3文档看起来相对没有文档。 p>
我班级的准系统示例如下: p>
在我的函数'myGC()'中我应该对数组做一个foreach并将我遇到的每个元素设置为NULL(我记得在C ++中做)或者设置$ this-&gt; _var = NULL free not not 只有指向数组的指针,还有与指针相关的所有元素? p>
div> class foo {
private $ _var;
public function __construct(){
$ this-&gt; _var = array();
for($ i = 0; $ i&lt; 10000000000; $ i ++){
$ this-&gt; _var [rand(1,100000)] ='我是字符串'。$ i。' 在数组';
}
}
公共函数myGC(){
$ this-&gt; _var = null;
}
}
code> pre>
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>';
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();