【问题标题】:php < 5.3 garbage collection, do array values need to be set null or does setting the array = null orphan all its elements?php < 5.3 垃圾收集,是否需要将数组值设置为 null 或设置 array = null 孤立其所有元素?
【发布时间】:2011-06-17 02:22:24
【问题描述】:

所以我正在使用 php 5.2 并且需要一些垃圾收集,因为我正在处理非常有限的资源和大型数据集。

从我的测试中,我看到 unset 在脚本结束之前什么都不做(即使我内存不足),这似乎与文档有点相反,尽管我假设我也在阅读 5.3 文档不是 5.2 文档,而且 5.3 文档似乎相对没有文档。

我的班级的准系统示例如下:

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

在我的函数“myGC()”中,我应该对数组进行 foreach 并将遇到的每个元素设置为 NULL(就像我记得在 C++ 中所做的那样)还是设置 $this->_var = NULL 不仅释放指针到数组以及与指针关联的所有元素?

【问题讨论】:

  • 你如何测试你的内存使用情况?通常只需取消引用分配的值即可。您应该记住,gc 仅在间隔中调用。
  • 我在 var 初始化之前设置了一个 memory_get_usage(),在它被销毁以考虑使用内存的其他 var 之前,然后在它被取消设置之后。内存在我跟踪的每次迭代中不断增长,在未设置匹配之前和之后,直到我触发内存不足错误,然后脚本执行突然停止。我应该在我的 destruct 方法中添加一个 echo 来验证 destruct 是否被调用过。(我很确定它从来没有被调用过,至少我的内存日志让我相信)

标签: php arrays memory garbage-collection


【解决方案1】:

你没有在任何地方调用 myGC(),这是问题所在吗?

要测试关于 unset 不起作用的假设,请尝试运行以下示例。如果它失败了,你的假设是正确的。如果不是 - 您还有其他错误。

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

【讨论】:

    【解决方案2】:

    设置$this-&gt;_var = NULL 就足够了,这将为$this-&gt;_var 设置的所有内容释放内存。

    你可以用这个(伪代码)测试它

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

    【讨论】:

      猜你喜欢
      • 2011-02-25
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 2017-03-13
      • 1970-01-01
      • 2012-11-30
      • 1970-01-01
      • 2018-09-25
      相关资源
      最近更新 更多