PHP Garbage Collection

PHP performs garbage collection at three primary junctures:

  1. When you tell it to
  2. When you leave a function
  3. When the script ends

PHP garbage collection works on reference count.

unset your global variables as soon as you don’t need them. PHP keeps a reference count for all variables and destroys them (in most conditions) as soon as this reference count goes to zero. Objects have one internal reference count and the variables themselves (the object references) each have one reference count. When all the object references have been destroyed because their reference coutns have hit 0, the object itself will be destroyed.

 

Example:

$a = new stdclass; //$a zval refcount 1, object refcount 1
$b = $a;           //$a/$b zval refcount 2, object refcount 1
//this forces the zval separation because $b isn't part of the reference set:
$c = &$a;          //$a/$c zval refcount 2 (isref), $b 1, object refcount 2
unset($c);         //$a zval refcount 1, $b 1, object refcount 2
unset($a);         //$b refcount 1, object refcount 1
unset($b);         //everything is destroyed

But consider the following scenario:

class A {
    public $b;
}
class B {
    public $a;
}

$a = new A;
$b = new B;
$a->b = $b;
$b->a = $a;
unset($a); //cannot destroy object $a because $b still references it
unset($b); //cannot destroy object $b because $a still references it

These cyclic references are where PHP 5.3’s garbage collector kicks in. You can explicitly invoke the garbage collector with gc_collect_cycles.

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s