the difference between unset and = null

后端 未结 5 1756
暖寄归人
暖寄归人 2020-11-29 04:03

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 fast

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 04:34

    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.

提交回复
热议问题