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?
-
And now I just realized that this is a clear duplicate. So I'm gonna vote to close.markus– markus2011年11月19日 15:37:58 +00:00Commented Nov 19, 2011 at 15:37
3 Answers 3
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.
3 Comments
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.
Comments
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.