1

Possible Duplicate:
Is there garbage collection in PHP?

In java there is a concept called Garbage Collector. In java an Object becomes Eligible for Garbage Collection when it's not reachable from any live threads or any static refrences in other words you can say that an object becomes eligible for garbage collection if its all references are null.

What will happen in PHP? Will it lead to a memory overflow. Is this a disadvantage in PHP or is there ways to handle and what are the ways and techniques PHP provides to handle memory efficiently?

asked Nov 19, 2011 at 15:30
1
  • And now I just realized that this is a clear duplicate. So I'm gonna vote to close. Commented Nov 19, 2011 at 15:37

3 Answers 3

4

Most important about php, that it has GC based on reference count. See example:

$a = 8;
unset($a); //memory free
$a = 8;
$b = &$a; //or even $b = $a, see below
unset($a); //memory unchanged

And php links all data at each other, before it is changed:

$a = 8;
$b = $a; //we use memory only for $a
$b++; //now we use twice more memory

That's a good approach for scripting language, because you can transfer objects between different layers of your app (e.g. move data this way M->C->V in MVC) and don't think about pointers or memory usage.

But, if you do smth like this (example from docs):

$a = array( 'one' );
$a[] =& $a;

You won't be able to clean up memory at all. This is tipical situation, when we have some main glue class application in MVC, that is stored in each object. We won't be able to clean up memory in this case. But, it's not that importatnt for scripting language with lifetime of several ms.

answered Nov 19, 2011 at 15:53
Sign up to request clarification or add additional context in comments.

3 Comments

PHP 5.3 should be able to free the memory in the last example.
Thanks, I'll make a test on Monday.
Sorry for late answer, but I don't work with php now. Browsed through docs. You still can rely on my answer, afaik. Much work was done inside of php engine, but basic features of reference counting GC remain the same.
3

PHP does have a garbage collector, but previous to PHP 5.3 (5.2?) it could not handle circular references and would be unable to GC certain constructs,. e.g.

$a = &$a;

would cause a memory leak. PHP will not run the GC unless it has to, as a GC run is expensive, and usually not needed as most PHP scripts are short-lived. The GC will kick in only when memory pressure is present, and you'll get an OOM error only if enough memory can't be freed at all.

answered Nov 19, 2011 at 15:35

Comments

2

PHP does garbage collection too, in fact, in PHP you very rarely have to think about memory at all. In PHP 5.3 garbage collection has been considerably improved. Read about it in the PHP manual.

answered Nov 19, 2011 at 15:34

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.