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?
Regarding objects, especially in lazy-load scenario, one should consider garbage collector is running in idle CPU cycles, so presuming you're going into trouble when a lot of objects are loading small time penalty will solve the memory freeing.
Use time_nanosleep to enable GC to collect memory. Setting variable to null is desirable.
Tested on production server, originally the job consumed 50MB and then was halted. After nanosleep was used 14MB was constant memory consumption.
One should say this depends on GC behaviour which may change from PHP version to version. But it works on PHP 5.3 fine.
eg. this sample (code taken form VirtueMart2 google feed)
It was mentioned in the unset manual's page in 2009:
(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: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.)I still doubt about this, but I've tried it at my script and I'm using xdebug to know how it will affect my app memory usage. The script is set on my function like this :
And I add unset just before the
return
code and it give me : 160200 then I try to change it with$sql = NULL
and it give me : 160224 :)But there is something unique on this comparative when I am not using unset() or NULL, xdebug give me 160144 as memory usage
So, I think giving line to use unset() or NULL will add process to your application and it will be better to stay origin with your code and decrease the variable that you are using as effective as you can .
Correct me if I'm wrong, thanks
unset
is not actually a function, but a language construct. It is no more a function call than areturn
or aninclude
.Aside from performance issues, using
unset
makes your code's intent much clearer.It works in a different way for variables copied by reference:
It makes a difference with array elements.
Consider this example
Here, the key 'test' still exists. However, in this example
the key no longer exists.