Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - what's the benefit of unsetting variables? [duplicate]

Tags:

php

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

Is there a real benefit of unsetting variables in php?

class test {    public function m1($a, $b)     $c = $a + $b;     unset($a, $b);     return $c;   } } 

Is it true that unsetting variables doesn't actually decrease the memory consumption during runtime?

like image 805
n00b Avatar asked Feb 17 '11 14:02

n00b


People also ask

What's better at freeing memory with PHP unset () or $var Null?

null variable: It speedily frees the memory.

What is the use of unset in PHP?

The unset() function in PHP resets any variable. If unset() is called inside a user-defined function, it unsets the local variables. If a user wants to unset the global variable inside the function, then he/she has to use $GLOBALS array to do so.

Does PHP unset free memory?

unset() does just what its 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.

How do you unset multiple variables in PHP?

IF you want to do this using loop then use for loop. Show activity on this post. You have to use for loop for this. you can use foreach loop but it will not unset all variable one variable still remains.


1 Answers

Is it true that unsetting variables doesn't actually decrease the memory consumption during runtime?

Yep. From PHP.net:

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.

Regarding your other question:

And is there any reason to unset variables apart from destroying session varaibles for instance or for scoping?

Not really, you pretty much summed it.

like image 81
Aron Rotteveel Avatar answered Oct 06 '22 13:10

Aron Rotteveel