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

前端 未结 13 2005
陌清茗
陌清茗 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条回答
  •  旧时难觅i
    2020-11-22 09:41

    By doing an unset() on a variable, you've essentially marked the variable for 'garbage collection' (PHP doesn't really have one, but for example's sake) so the memory isn't immediately available. The variable no longer houses the data, but the stack remains at the larger size. Doing the null method drops the data and shrinks the stack memory almost immediately.

    This has been from personal experience and others as well. See the comments of the unset() function here.

    I personally use unset() between iterations in a loop so that I don't have to have the delay of the stack being yo-yo'd in size. The data is gone, but the footprint remains. On the next iteration, the memory is already being taken by php and thus, quicker to initialize the next variable.

提交回复
热议问题