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?
I created a new performance test for
unset
and=null
, because as mentioned in the comments the here written has an error (the recreating of the elements). I used arrays, as you see it didn't matter now.But i can only test it on an PHP 5.5.9 server, here the results: - took 4.4571571350098 seconds - took 4.4425978660583 seconds
I prefer
unset
for readability reasons.PHP 7 is already worked on such memory management issues and its reduced up-to minimal usage.
PHP 7.1 Outpu:
took 0.16778993606567 seconds took 0.16630101203918 seconds
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.
unset
code if not freeing immediate memory is still very helpful and would be a good practice to do this each time we pass on code steps before we exit a method. take note its not about freeing immediate memory. immediate memory is for CPU, what about secondary memory which is RAM.and this also tackles about preventing memory leaks.
please see this link http://www.hackingwithphp.com/18/1/11/be-wary-of-garbage-collection-part-2
i have been using unset for a long time now.
better practice like this in code to instanly unset all variable that have been used already as array.
and
just unset($data);
to free all variable usage.please see related topic to unset
How important is it to unset variables in PHP?
[bug]
For the record, and excluding the time that it takes:
It returns
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)
Per that it seems like "= null" is faster.
PHP 5.4 results:
PHP 5.3 results:
PHP 5.2 results:
PHP 5.1 results:
Things start to look different with PHP 5.0 and 4.4.
5.0:
4.4:
Keep in mind microtime(true) doesn't work in PHP 4.4 so I had to use the microtime_float example given in php.net/microtime / Example #1.