34

I am somewhat new to PHP, and I am wondering:

How important is it to unset variables in PHP?

I know in languages like C, we free the allocated memory to prevent leaks, etc. By using unset on variables when I am done with them, will this significantly increase performance of my applications?

Also, is there a benchmark anywhere that compares the difference between using unset and not using unset?

Geoffrey
  • 5,407
  • 10
  • 43
  • 78
dd0x
  • 520
  • 1
  • 5
  • 7
  • *(related)* http://www.php.net/manual/en/features.gc.refcounting-basics.php and http://blog.preinheimer.com/index.php?/archives/354-Memory-usage-in-PHP.html – Gordon Apr 11 '10 at 16:17
  • Thanks for those links. They give excellent explanations. – dd0x Apr 11 '10 at 16:29

4 Answers4

54

See this example (and the article I linked below the question):

$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      // 120172
echo memory_get_peak_usage() . "<br>\n"; // 121248

$x = str_repeat('x', 80000);
echo memory_get_usage() . "<br>\n";      // 120172
echo memory_get_peak_usage() . "<br>\n"; // 201284

As you can see, at one point PHP had used up almost double the memory. This is because before assigning the 'x'-string to $x, PHP builds the new string in memory, while holding the previous variable in memory, too. This could have been prevented with unsetting $x.

Another example:

for ($i=0; $i<3; $i++) {
    $str = str_repeat("Hello", 10000);
    echo memory_get_peak_usage(), PHP_EOL;
}

This will output something like

375696
425824
425824

At the first iteration $str is still empty before assignment. On the second iteration $str will hold the generated string though. When str_repeat is then called for the second time, it will not immediately overwrite $str, but first create the string that is to be assigned in memory. So you end up with $str and the value it should be assigned. Double memory. If you unset $str, this will not happen:

for($i=0;$i<3;$i++) {
    $str = str_repeat("Hello", 10000);
    echo memory_get_peak_usage(), PHP_EOL;
    unset($str);
}

// outputs something like
375904
376016
376016

Does it matter? Well, the linked article sums it quite good with

This isn't critical, except when it is.

It doesn't hurt to unset your variables when you no longer need them. Maybe you are on a shared host and want to do some iterating over large datasets. If unsetting would prevent PHP from ending with Allowed memory size of XXXX bytes exhausted, then it's worth the tiny effort.

What should also be taken into account is, that even if the request lifetime is just a second, doubling the memory usage effectively halves the maximum amount of simultaneous requests that can be served. If you are nowhere close to the server's limit anyway, then who cares, but if you are, then a simple unset could save you the money for more RAM or an additional server.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • In a current project I am using PHP to generate a number of HTML pages of variable size by moving through a loop, so I should definitely unset the variable which is holding the contents at the end of each loop. That could potentially be 'critical' correct? – dd0x Apr 11 '10 at 17:22
  • @dd0x In theory, yes. But in practise, you should use something like XDebug to profile your application to see if it is really critical. I consider unsetting in PHP much more of a scaling optimization than an absolute necessity. – Gordon Apr 11 '10 at 17:31
  • @dd0x Just to add, PHP has a garbage collector which ensures that 99.9% of the time you don't have to worry. – Yacoby Apr 11 '10 at 21:11
  • @Yacoby I've linked the GC pages below the question ;) and PHP would still use double the memory in the example above, even with the GC enabled. – Gordon Apr 11 '10 at 21:51
  • "it isn't critical, except when it is." This is very import for large project, you will hit this wall and spend a lot of time trying to fix it. I would recommend using it on large vars. – Dillon Burnett Jan 28 '17 at 05:07
9

There are many situations in which unset will not actually deallocate much of anything, so its use is generally quite pointless unless the logical flow of your code necessitates its non-existence.

Azeem.Butt
  • 5,855
  • 1
  • 26
  • 22
  • 3
    It should also be said that all memory is freed at the end of script execution anyway, so unsetting before the end of execution will do little good (and may even be detrimental) for performance. – mattbasta Apr 11 '10 at 16:38
4

Applications being written in languages like C usually run for many hours. But usual php application's runtime is just about 0.05 sec. So, it is much less important to use unset.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 6
    While it may be true it isn't the right answer. I have run scripts PHP for days. As PHP is garbage collected the amount of time a script has been running is for the most part irrelevant. – Yacoby Apr 11 '10 at 17:05
  • 2
    The answer also gives the impression that `unset` would be required in a long running script and that `unset` is the equivalent of `free`. – Yacoby Apr 11 '10 at 17:11
  • @Yacoby "*I have run scripts PHP for days*" Perhaps you need to look at using something else for such specific tasks. PHP is more suited for web applications, and web pages do not need to run for days. Of course, web servers are far more powerful now 5 years on (even cheap hosting ones for £3 per month) and PHP garbage collection is improved. Unsetting variables for freeing up resource is not advised. – James Jun 26 '15 at 13:48
0

It depends, you should make sure you unsetted very long strings (such as a blog post's content selected from a db).

<?php
$post = get_blog_post();
echo $post;
unset($post);
?>
Ming-Tang
  • 17,410
  • 8
  • 38
  • 76