Reputation: 4029
Do I need to worry about memory leaks with PHP? In particular, I have the following code that is being called from a browser. When the call finishes, is everything cleaned up properly, or, do I need to clear the memory created by the first array that was created?
class SomeClass
{
var $someArray = array();
function someMethod()
{
$this->someArray[1] = "Some Value 1";
$this->someArray[2] = "Some Value 2";
$this->someArray[3] = "Some Value 3";
$this->someArray = array();
$this->someArray[1] = "Some other Value";
$this->someArray[2] = "Some other Value";
$this->someArray[3] = "Some other Value";
}
}
someMethod();
Thanks, Scott
Upvotes: 1
Views: 724
Reputation: 91983
There actually do exist memory problems if you run mod_php through Apache with the mpm_prefork behavior. The problem is that memory consumed by PHP is not released back to the operating system. The same Apache process can reuse the memory for subsequent requests, but it can't be used by other programs (not even other Apache processes).
One solution is to restart the processes from time to time, for example by setting the MaxRequestsPerChild setting to something rather low (100 or so, maybe lower for lightly loaded servers). The best solution is to not use mod_php at all but instead run PHP through FastCGI.
This is a sysadmin issue though, not a programmer issue.
Upvotes: 1
Reputation: 490637
Do I need to worry about memory leaks with PHP?
It's possible to have a cyclic reference in PHP where the refcount
of the zval
never drops to 0
. This will cause a memory leak (GC won't clean up objects that have a reference to them). This has been fixed in >= PHP 5.3.
In particular, I have the following code that is being called from a browser. When the call finishes, is everything cleaned up properly, or, do I need to clear the memory created by the first array that was created?
PHP scripts have a request lifecycle (run application, return response, close application), so it shouldn't be a worry. All memory used by your application should be marked as free'd when your application finishes, ready to be overwritten on the next request.
Upvotes: 3
Reputation: 33467
If you're super paranoid, you can always unset
things, however, PHP is a garbage collected language meaning that unless there is a bug in the core or in an extension, there is never going to be a memory leak.
On a side note, you should use the newer PHP 5 OOP syntax. And, someMethod would be an error. It would need to be $obj->someMethod() where $obj is an instance of the class.
Upvotes: 1