Does php unset free memory?

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?

asked Feb 25, 2009 at 6:33

Does php unset free memory?

alexalex

467k197 gold badges865 silver badges975 bronze badges

It was mentioned in the unset manual's page in 2009:

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.

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.

(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:

$a = str_repeat('hello world ', 100);
unset($a);
var_dump($a);

Outputs:

Notice: Undefined variable: a in xxx
NULL

But when $a = null is used:

$a = str_repeat('hello world ', 100);
$a = null;
var_dump($a);

Outputs:

NULL

It seems that $a = null is a bit faster than its unset() counterpart: updating a symbol table entry appears to be faster than removing it.


  • when you try to use a non-existent (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.)
  • A variable with null assigned to it is still a perfectly normal variable though.

Does php unset free memory?

Al Foиce ѫ

4,05512 gold badges37 silver badges46 bronze badges

answered Feb 25, 2009 at 6:50

Does php unset free memory?

VonCVonC

1.2m492 gold badges4145 silver badges4890 bronze badges

13

unset is not actually a function, but a language construct. It is no more a function call than a return or an include.

Aside from performance issues, using unset makes your code's intent much clearer.

answered Feb 25, 2009 at 8:55

Alex BarrettAlex Barrett

15.7k3 gold badges50 silver badges51 bronze badges

7

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.

answered Feb 25, 2009 at 6:45

William HolroydWilliam Holroyd

3,3441 gold badge20 silver badges25 bronze badges

3


Per that it seems like "= null" is faster.

PHP 5.4 results:

  • took 0.88389301300049 seconds
  • took 2.1757180690765 seconds

PHP 5.3 results:

  • took 1.7235369682312 seconds
  • took 2.9490959644318 seconds

PHP 5.2 results:

  • took 3.0069220066071 seconds
  • took 4.7002630233765 seconds

PHP 5.1 results:

  • took 2.6272349357605 seconds
  • took 5.0403649806976 seconds

Things start to look different with PHP 5.0 and 4.4.

5.0:

  • took 10.038941144943 seconds
  • took 7.0874409675598 seconds

4.4:

  • took 7.5352551937103 seconds
  • took 6.6245851516724 seconds

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.

answered Nov 26, 2012 at 4:12

5

It works in a different way for variables copied by reference:

$a = 5;
$b = &$a;
unset($b); // just say $b should not point to any variable
print $a; // 5

$a = 5;
$b = &$a;
$b = null; // rewrites value of $b (and $a)
print $a; // nothing, because $a = null

Antti29

2,91512 gold badges36 silver badges36 bronze badges

answered Aug 2, 2012 at 2:32

Does php unset free memory?

RiaDRiaD

45.8k10 gold badges75 silver badges119 bronze badges

2

It makes a difference with array elements.

Consider this example

$a = array('test' => 1);
$a['test'] = NULL;
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";

Here, the key 'test' still exists. However, in this example

$a = array('test' => 1);
unset($a['test']);
echo "Key test ", array_key_exists('test', $a)? "exists": "does not exist";

the key no longer exists.

answered Mar 26, 2011 at 11:03

Does php unset free memory?

aurisauris

6816 silver badges5 bronze badges

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)

for($n=0; $n" . memory_get_usage() . "";//$ids[$n];
        time_nanosleep(0, 10000000);
    }

    $product = $productModel->getProductSingle((int)$ids[$n],true, true, true);
    ...

answered Nov 19, 2012 at 20:23

Does php unset free memory?

OSPOSP

1,4091 gold badge14 silver badges15 bronze badges

For the record, and excluding the time that it takes:

First:
"; $x = str_repeat('x', 80000); echo memory_get_usage() . "
\n"; echo memory_get_peak_usage() . "
\n"; echo "
Unset:
"; unset($x); $x = str_repeat('x', 80000); echo memory_get_usage() . "
\n"; echo memory_get_peak_usage() . "
\n"; echo "
Null:
"; $x=null; $x = str_repeat('x', 80000); echo memory_get_usage() . "
\n"; echo memory_get_peak_usage() . "
\n"; echo "
function:
"; function test() { $x = str_repeat('x', 80000); } echo memory_get_usage() . "
\n"; echo memory_get_peak_usage() . "
\n"; echo "
Reasign:
"; $x = str_repeat('x', 80000); echo memory_get_usage() . "
\n"; echo memory_get_peak_usage() . "
\n";

It returns

First:

Unset:

Null:

function:

Reasign:
438296
520216 <-- double usage.

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)

answered Jul 1, 2017 at 23:59

Does php unset free memory?

magallanesmagallanes

6,2874 gold badges51 silver badges52 bronze badges

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

answered Jun 27, 2018 at 5:54

Code example from comment

echo "PHP Version: " . phpversion() . PHP_EOL . PHP_EOL;

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    $a = NULL;
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;



$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    $a = 'a';
    unset($a);
}
$elapsed = microtime(true) - $start;

echo "took $elapsed seconds" . PHP_EOL;

Running in docker container from image php:7.4-fpm and others..

PHP Version: 7.4.8
took 0.22569918632507 seconds null
took 0.11705803871155 seconds unset
took 0.20791196823121 seconds null
took 0.11697316169739 seconds unset

PHP Version: 7.3.20
took 0.22086310386658 seconds null
took 0.11882591247559 seconds unset
took 0.21383500099182 seconds null
took 0.11916995048523 seconds unset

PHP Version: 7.2.32
took 0.24728178977966 seconds null
took 0.12719893455505 seconds unset
took 0.23839902877808 seconds null
took 0.12744522094727 seconds unset

PHP Version: 7.1.33
took 0.51380109786987 seconds null
took 0.50135898590088 seconds unset
took 0.50358104705811 seconds null
took 0.50115609169006 seconds unset

PHP Version: 7.0.33
took 0.50918698310852 seconds null
took 0.50490307807922 seconds unset
took 0.50227618217468 seconds null
took 0.50514912605286 seconds unset

PHP Version: 5.6.40
took 1.0063569545746 seconds null
took 1.6303179264069 seconds unset
took 1.0689589977264 seconds null
took 1.6382601261139 seconds unset

PHP Version: 5.4.45
took 1.0791940689087 seconds null
took 1.6308979988098 seconds unset
took 1.0029168128967 seconds null
took 1.6320278644562 seconds unset

But, with other example:

Results:

PHP Version: 7.4.8
took 0.053696155548096 seconds
took 0.053897857666016 seconds

PHP Version: 7.3.20
took 0.054572820663452 seconds
took 0.054342031478882 seconds

PHP Version: 7.2.32
took 0.05678391456604 seconds
took 0.057311058044434 seconds


PHP Version: 7.1.33
took 0.097366094589233 seconds
took 0.073100090026855 seconds

PHP Version: 7.0.33
took 0.076443910598755 seconds
took 0.077098846435547 seconds

PHP Version: 7.0.33
took 0.075634002685547 seconds
took 0.075317859649658 seconds

PHP Version: 5.6.40
took 0.29681086540222 seconds
took 0.28199100494385 seconds

PHP Version: 5.4.45
took 0.30513095855713 seconds
took 0.29265689849854 seconds

answered Jul 12, 2020 at 10:59

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 :

function gen_table_data($serv, $coorp, $type, $showSql = FALSE, $table = 'ireg_idnts') {
    $sql = "SELECT COUNT(`operator`) `operator` FROM $table WHERE $serv = '$coorp'";
    if($showSql === FALSE) {
        $sql = mysql_query($sql) or die(mysql_error());
        $data = mysql_fetch_array($sql);
        return $data[0];
    } else echo $sql;
}

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

answered Nov 28, 2012 at 2:14

Anggie AzizAnggie Aziz

1331 gold badge1 silver badge10 bronze badges

1

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.

';

$start = microtime(true);
for ($i = 0; $i < 10000000; $i++) {
    unset($arr2[$i]);
}
$elapsed = microtime(true) - $start;

echo 'took '. $elapsed .'seconds
';

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.

answered Jun 9, 2015 at 17:28

Does php unset free memory?

Michael B.Michael B.

7578 silver badges14 bronze badges

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.

$data['tesst']='';
$data['test2']='asdadsa';
....
nth.

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]

answered Oct 29, 2015 at 19:53

zero8zero8

1,8893 gold badges14 silver badges25 bronze badges

Does PHP unset clear 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 does PHP manage memory?

PHP memory management functions are invoked by the MySQL Native Driver through a lightweight wrapper. Among others, the wrapper makes debugging easier. The various MySQL Server and the various client APIs differentiate between buffered and unbuffered result sets.

What does PHP unset do?

unset() destroys the specified variables. The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy. If a globalized variable is unset() inside of a function, only the local variable is destroyed.

Is unset variable used in PHP?

The unset() function is an inbuilt function in PHP which is used to unset a specified variable.