Skip to content
Advertisement

the difference between unset and = null

From a random php.net post:

If you are doing $whatever = null; then you are rewriting variable’s data. You might get memory freed / shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.

Apparently this is the undisputed truth so maybe someone would be so kind as to explain.

I mean, what, does unset magically not execute any assembly instructions whereas $whatever = null; does? The answer, as given, is about as useful as saying

$whatever = null resets the buffer and the L1 cache whereas unset clears the buffer and resets the L2 cache.

Techno mumbo jumbo doesn’t constitute an answer.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement