Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between $var = null and unset($var) [duplicate]

Tags:

php

Possible Duplicate:
What's better at freeing memory with PHP: unset() or $var = null

As far as the garbage collection goes, is 1 better than the other in any circumstances?

EDIT: Particularly if $var is a very large variable with a lot of levels of recursion and other objects (so to do with recursive cleanup of large objects)

EDIT: Removed this: I can think of only 1 thing, and that's that isset($var) will respond differently in either case.

Because apparently I was mistaken... They both react the same.

like image 880
Ricky Cook Avatar asked Jan 16 '23 22:01

Ricky Cook


2 Answers

unset($var);
// You will get Undefined variable Notice.
if ($var) {}

$var = null;
// it's ok.
if ($var) {}

Addition of GC of php.

PHP's Garbage Collection is based on the refcount of the zval, if refcount becomes 0, then the zval can be freed.

So if $a = $b = array(/*a very large array*/);, unset only $a or only $b won't free the memory of the large array.

unset($a); or $a = null or assign another value to $a will all let the refcount decrease by 1, but the memory will be freed only when the refcount decrease to 0.

like image 169
xdazz Avatar answered Jan 22 '23 10:01

xdazz


unset does not force immediate memory freeing but leaves it for the gc. $var = null; however forces immediate memory release.

See example:

 // $a = NULL; (better I think)
 $a = 5;
 $b = & $a;
 $a = NULL;
 print "b $b "; // b 
 print(! isset($b)); // 1 
 ?>

It is also worthy to note that in the case of an array unset destroys the variable completely. i.e.:

<?php
$ar = array(1,2,3,4);
var_dump($ar);
echo "<br />";

unset($ar[2]);
var_dump($ar);
echo "<br />";

$ar[1] = null;
var_dump($ar);
?>

Returns the output:

array(4) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) } 
array(3) { [0]=> int(1) [1]=> int(2) [3]=> int(4) } 
array(3) { [0]=> int(1) [1]=> NULL [3]=> int(4) }
like image 39
rtuner Avatar answered Jan 22 '23 12:01

rtuner