An important difference between both methods is that unset($a)
also removes $a
from the symbol table; for example:
$a = str_repeat('hello world ', 100);
unset($a);
var_dump($a);
Outputs:
Notice: Undefined variable: a in xxx
NULL
But when $a = null
is used:
$a = str_repeat('hello world ', 100);
$a = null;
var_dump($a);
Outputs:
NULL
I ran the code through a benchmark as well and found that $a = null
is roughly 6% faster than its unset()
counterpart. It seems that updating a symbol table entry is faster than removing it.
Addendum
The other difference (as seen in this small script) seems to be how much memory is restored after each call:
echo memory_get_usage(), PHP_EOL;
$a = str_repeat('hello world ', 100);
echo memory_get_usage(), PHP_EOL;
// EITHER unset($a); OR $a = null;
echo memory_get_usage(), PHP_EOL;
When using unset()
all but 64 bytes of memory are given back, whereas $a = null;
frees all but 272 bytes of memory. I don't have enough knowledge to know why there's a 208 bytes difference between both methods, but it's a difference nonetheless.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…