douningchang3610 2009-02-25 06:33
浏览 162
已采纳

使用PHP释放内存有什么好处:unset()或$ var = null

I realise the second one avoids the overhead of a function call (update, is actually a language construct), but it would be interesting to know if one is better than the other. I have been using unset() for most of my coding, but I've recently looked through a few respectable classes found off the net that use $var = null instead.

Is there a preferred one, and what is the reasoning?

  • 写回答

12条回答 默认 最新

  • dongxu3029 2009-02-25 06:50
    关注

    It was mentioned in the unset manual's page in 2009:

    unset() does just what its name says - unset a variable. It does not force immediate memory freeing. PHP's garbage collector will do it when it see fits - by intention as soon, as those CPU cycles aren't needed anyway, or as late as before the script would run out of memory, whatever occurs first.

    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.

    (Since 2013, that unset man page don't include that section anymore)

    Note that until php5.3, if you have two objects in circular reference, such as in a parent-child relationship, calling unset() on the parent object will not free the memory used for the parent reference in the child object. (Nor will the memory be freed when the parent object is garbage-collected.) (bug 33595)


    The question "difference between unset and = null" details some differences:


    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
    

    It seems that $a = null is a bit faster than its unset() counterpart: updating a symbol table entry appears to be faster than removing it.


    • when you try to use a non-existent (unset) variable, an error will be triggered and the value for the variable expression will be null. (Because, what else should PHP do? Every expression needs to result in some value.)
    • A variable with null assigned to it is still a perfectly normal variable though.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 如何实验stm32主通道和互补通道独立输出
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题