If I am using a tree structure of nodes similar to the code below, do I have to worry about the circular reference?
I have read that PHP uses a memory allocation mechanism which can make life very hard for the garbage collector when there are circular references involved.
What I want to know is:
- If my tree consists of only a few nodes, say 25, is this a problem?
- Will the memory be freed at the end of the script or am I slowly creating a problem for the server?
- Under what circumstances will this problem have an effect during script execution?
- Will manually destroying the references solve the problem and should I always do it?
class Node { private $parent; private $children; function addChild( Node $child ) { $this->children[] = $child; $child->setParent( $this ); } function setParent( $parent ) { $this->parent = $parent; } } //eg $node0 = new Node; $node1 = new Node; // nodes 1 and 2 have a circular reference to each other $node0->addChild( $node1 );
Point by point:
Not unless your nodes are real monsters.
When the interpreter shuts down all the memory is released.
I doubt you will have anything to worry about unless you have very low memory limits or very large dynamic data structures. If you have 25 nodes that aren’t being created/freed frequently you won’t have an issue.
It will help. When loading a large data set into our database with Propel we ran into a lot of problem with memory consumption that we tracked to circular references not being freed. Our solution was to call a method that cleared all references.