Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best method for memory cleanup in PHP? (5.2)

I have two simple questions. What is better/useful for memory cleanup.

$var = null;

or

unset($var);

I have one function with one cycle. I am getting (after few minutes)

Fatal error: Allowed memory size of 419430400 bytes exhausted

I am setting null and unset()-ing every object (at the end of the cycle) but still without any success :( I cant find out what is consuming memory.

And what about function calls in cycle? Will PHP release all allocations in these functions?(after call)

like image 656
Michal Drozd Avatar asked Aug 05 '10 08:08

Michal Drozd


2 Answers

PHP itself confuses both concepts sometimes but, in general, a variable set to NULL is not the same as a variable that does not exist:

<?php

$foo = 'One';
$bar = 'Two';

$foo = NULL;
unset($bar);

var_dump($foo); // NULL
var_dump($bar); // Notice: Undefined variable: bar
var_dump(get_defined_vars()); // Only foo shows up: ["foo"]=> NULL

?>
like image 87
Álvaro González Avatar answered Sep 20 '22 14:09

Álvaro González


unset() does just that, it unsets a variable; but it does not immediate free up memory.

PHP's garbage collector will actually free up memory previously used by variables that are now unset, but only when it runs. This could be sooner, when CPU cycles aren't actively being used for other work, or before the script would otherwise run out of memory... whichever situation occurs first.

And be aware that unset won't necessarily release the memory used by a variable if you have other references to that variable. It will simply delete the reference, and reduce the reference count for the actual stored data by 1.

EDIT While unset doesn't immediately release the memory used (only garbage collection actually does that) the memory that is no longer used as a result is available for the declaration of new variables

like image 24
Mark Baker Avatar answered Sep 21 '22 14:09

Mark Baker