My question is really simple, I fetch data from database and store them as variable for future use. After done working with the variables, is it cost-efficient to use the unset function of PHP to free up the memory? What I mean by 'cost-efficient' is whether is it worth calling the function multiple times in hope of clearing the memory to reduce up page load time.
3 Answers
As mentioned in unset
From here
"unset() does just what it's 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."
-
2You might want to add that you are quoting a user comment, not the php documentation itself. – jeroen Jun 25 '12 at 16:16
Use unset when you are dealing with huge data like if you are dealing with arrays.

- 711
- 4
- 10
- 27
-
Maybe this link is helpful for you too: http://stackoverflow.com/questions/3298206/php-when-to-use-unset – user1149244 Jun 25 '12 at 16:18
You do not really need to call the function multiple times unless you use the same variable name for different values - which I do not recommend.
unset($variable1, $variable2, $variable3)
I use unset at the end of my loops and to unset my arrays at the end of my code.
I do not really need to use unset unless I really have to - loops again here for a known php weirdness - or I have really huge arrays.

- 2,194
- 1
- 18
- 28