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

前端 未结 13 1985
陌清茗
陌清茗 2020-11-22 08:57

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 be

13条回答
  •  粉色の甜心
    2020-11-22 09:37

    For the record, and excluding the time that it takes:

    First:
    "; $x = str_repeat('x', 80000); echo memory_get_usage() . "
    \n"; echo memory_get_peak_usage() . "
    \n"; echo "
    Unset:
    "; unset($x); $x = str_repeat('x', 80000); echo memory_get_usage() . "
    \n"; echo memory_get_peak_usage() . "
    \n"; echo "
    Null:
    "; $x=null; $x = str_repeat('x', 80000); echo memory_get_usage() . "
    \n"; echo memory_get_peak_usage() . "
    \n"; echo "
    function:
    "; function test() { $x = str_repeat('x', 80000); } echo memory_get_usage() . "
    \n"; echo memory_get_peak_usage() . "
    \n"; echo "
    Reasign:
    "; $x = str_repeat('x', 80000); echo memory_get_usage() . "
    \n"; echo memory_get_peak_usage() . "
    \n";

    It returns

    First:
    438296
    438352
    Unset:
    438296
    438352
    Null:
    438296
    438352
    function:
    438296
    438352
    Reasign:
    438296
    520216 <-- double usage.
    

    Conclusion, both null and unset free memory as expected (not only at the end of the execution). Also, reassigning a variable holds the value twice at some point (520216 versus 438352)

提交回复
热议问题