Setting first and last node object identifier to NULL should result in instant automatic garbage collection of all node object inside a linked list because there is no reference to all node objects including first and last node.
$this->first = NULL
$this->last = NULL
Do we need to iterate over the complete linked list and unset each of the node object identifier one by one?
My belief is that setting first and last to NULL is sufficient and PHP does garbage collection in background on our behalf.
Please correct me if i am wrong.
If you are running PHP <5.3.0 and you are using a doubly linked list, none of the nodes will be freed. This is because earlier PHP versions only used reference counting [1], which is unable to recognize cyclic references. Even in a singly linked list, it is possible that it would take ‘n’ passes of the garbage collector to free the entire list, depending on the exact algorithm used (though I see this unlikely).
To explain further, in a doubly linked list, every node points to the node both before and after it. Consider the ordered nodes A, B, C. This means that A is pointed to by, B, C is pointed to by B, and B is pointed to by A and C. Therefore, their references counts will always be non-zero unless you explicitly unset the nodes yourself.
With the singly linked list, and the same nodes A, B, C, each node is pointed to by the one previous, except A, which is pointed to by no other node. Therefore, if you remove the reference to A, it will be garbage collected. Then, since B no longer is pointed to, it will be freed, and so-on down the list. However, say the garbage collector visits the list in reverse or random order (rather than the optimal left to right). Then, it may look at B first and conclude A still points to it, and therefore does not need freeing. Then the GC frees A and is done. Although, it is more likely that the GC algorithm continually collects memory with zero reference counts until there is nothing more to collect, which would avoid this problem.
Thankfully, as of PHP 5.3.0, we don’t have to worry about the cyclic references [2]. This algorithm works by constructing a tree from the root memory node. Anything not included in the final tree must have been orphaned (and consequently is only being kept alive because of a cyclic reference), and therefore can be freed. So yes, as long as nothing else in your program points to any node in your list, the entire list will be freed by removing the references to the start and end.
Note that the algorithm to free orphaned cyclic references is more expensive than the simple reference counting. Explicit freeing code may or may not be beneficial. Careful benchmarking will have to be done to find this.
[1] http://www.php.net/manual/en/features.gc.refcounting-basics.php
[2] http://www.php.net/manual/en/features.gc.collecting-cycles.php