views:

18

answers:

1

I'm writing a simple linear linked list implementation in PHP. This is basically just for practice... part of a Project Euler problem. I'm not sure if I should be using unset() to help in garbage collection in order to avoid memory leaks. Should I include an unset() for head and temp in the destructor of LLL?

I understand that I'll use unset() to delete nodes when I want, but is unset() necessary for general clean up at any point?

Is the memory map freed once the script terminates even if you don't use unset()?

I saw this SO question, but I'm still a little unclear. Is the answer that you simply don't have to use unset() to avoid any sort of memory leaks associated with creating references?

I'm using PHP 5.. btw.

Unsetting references in PHP

PHP references tutorial

Here is the code - I'm creating references when I create $temp and $this->head at certain points in the LLL class:

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/>&nbsp;&nbsp;";
        if ($this->head)
        {               
            $temp =& $this->head;
            do
            {
                echo $temp->data . " ";
            } while ($temp =& $temp->next);
        } else
        {
            echo "is empty.";
        }
        echo "<br/>";
    }
}

Thanks!

+1  A: 

Is the memory map freed once the script terminates even if you don't use unset()?

Yes - when a script ends, all of the memory resources allocated by it are freed.

Amber