Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does PHP's gc_enable function do exactly?

Before you tell me to read the manual, check out the php.net documentation for this function:

Warning
This function is currently not documented; only its argument list is available.

That was helpful!

This page explains that it enables garbage collection for cyclic references. Where and when is this useful? Could someone show me an example of its use? Preferably an example where a cyclic reference is created and then collected.

like image 480
Stephen Avatar asked Jan 17 '11 16:01

Stephen


3 Answers

gc_enable is only needed if you call gc_disable. There is really no sane reason to do this, as that would cause cyclic references to not be garbage collected (like pre-5.3, when the cyclic GC did not exist).

PHP's garbage collector works by reference counting. You can think of a variable as a "pointer" to an object. When an object has no pointers to it, it is "dead" because nothing can reach it, so it is garbage collected.

//one thing points to the Foo object
$a = new Foo();

//now two things do
$b = $a;

//now only $b points to it
$a = null;

//now nothing points to Foo, so php garbage collects the object
$b = null;

Consider this though:

$a = new Foo();
$b = new Bar();
$b->foo = $a;
$a->bar = $b;

$a = $b = null;

At this point nothing is holding on to $a or $b except the objects themselves. This is a cyclic reference, and in previous versions of php (< 5.3), would not be collected. The cyclic collector in 5.3 can now detect this and clean up these objects.

like image 104
ryeguy Avatar answered Oct 22 '22 21:10

ryeguy


There is a full chapter on Garbage Collection in the PHP Manual explaining this:

  • Reference Counting Basics
  • Collecting Cycles
  • Performance Considerations

I usually try not to just link offsite, but feel it's too much to summarize.

like image 37
Gordon Avatar answered Oct 22 '22 21:10

Gordon


There are reasons why we use gc_disable and gc_enable.

In the latest PHP manual, it states

Can be very useful for big projects, when you create a lot of objects that should stay in memory. So GC can't clean them up and just wasting CPU time.

Issue in composer: https://github.com/composer/composer/pull/3482#issuecomment-65199153

Solution and people replies: https://github.com/composer/composer/commit/ac676f47f7bbc619678a29deae097b6b0710b799

Please be reminded that the second link above contains a lot of comments with graphics.

like image 3
Ivor Zhou Avatar answered Oct 22 '22 19:10

Ivor Zhou