Quick question.
I'm new to php and got confused with when to use the unset function. Should I unset everything I set or only when I want to guarantee it gets unset now?
Cheers, Diogo
Quick question.
I'm new to php and got confused with when to use the unset function. Should I unset everything I set or only when I want to guarantee it gets unset now?
Cheers, Diogo
There's a garbage collector in php, so you may use unset just in case you want to make sure your object / var is destroyed. It's usefull to make sure a $SESSION is destroyed for example.
You should only use unset if you want to gurantee that it is deleted from memory. This could be usefull if you process / manipulate / create a bunch of images or something really memory consuming.
Most of the time you do not need to bother about unsetting. PHP will handle unused variables for you. However, there is certain situations, for instance looping, where it helps reduce memory usage. Consider:
for($i=0;$i<3;$i++) {
$str = str_repeat("Hello", 10000);
echo memory_get_peak_usage(), PHP_EOL;
}
This will output something like
375696
425824
425824
At the first iteration $str is still empty before assignment. On the second iteration $str will hold the generated string though. When str_repeat is then called for the second time, it will not immediately overwrite $str, but first create the string that is to be assigned in memory. So you end up with $str and the value it should be assigned. Double memory. If you unset $str, this will not happen:
for($i=0;$i<3;$i++) {
$str = str_repeat("Hello", 10000);
echo memory_get_peak_usage(), PHP_EOL;
unset($str);
}
// outputs something like
375904
376016
376016
Most of the time it doesnt matter. But if you do memory intensive work, keep that in mind, because otherwise you might run into memory leaks quickly.
There is another case when unset() is recommended - foreach loops with references (example from PHP Manual):
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
$value = 10; // Without unset() this will change last value of the $arr