我正在用PHP编写一个简单的线性链表实现。这基本上只是为了练习…一部分
Project Euler
问题。我不确定是否应该使用
unset()
帮助垃圾收集以避免内存泄漏。我应该在lll的析构函数中包含head和temp的unset()吗?
我知道我会在需要的时候使用unset()删除节点,但是unset()在任何时候都是常规清理所必需的吗?
即使不使用unset(),脚本终止后内存映射是否释放?
I saw this SO question
但我还是有点不清楚。答案是您不必使用unset()来避免与创建引用相关联的任何类型的内存泄漏吗?
我用的是php 5……顺便说一句。
Unsetting references in PHP
PHP references tutorial
以下是代码-我在创建$temp和$this时创建引用->在lll类的某些点创建头:
class Node
{
public $data;
public $next;
}
class LLL
{
// The first node
private $head;
public function __construct()
{
$this->head = NULL;
}
public function insertFirst($data)
{
if (!$this->head)
{
// Create the head
$this->head = new Node;
$temp =& $this->head;
$temp->data = $data;
$temp->next = NULL;
} else
{
// Add a node, and make it the new head.
$temp = new Node;
$temp->next = $this->head;
$temp->data = $data;
$this->head =& $temp;
}
}
public function showAll()
{
echo "The linear linked list:<br/> ";
if ($this->head)
{
$temp =& $this->head;
do
{
echo $temp->data . " ";
} while ($temp =& $temp->next);
} else
{
echo "is empty.";
}
echo "<br/>";
}
}
谢谢!