Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does PHP free local variables immediately after the function ends?

Tags:

php

memory

The code illustrates better what I'm asking:

function foo(){

  $var = get_huge_amount_of_data();

  return $var[0];
}


$s = foo();

// is memory freed here for the $var variable created above?

do_other_stuff(); // need memory here lol

So I know that $var gets freed at some point, but does PHP do it efficiently? Or do I manually need to unset expensive variables?

like image 293
Anna K. Avatar asked Dec 29 '12 15:12

Anna K.


2 Answers

Yes it does get freed.

You can check this by using:

function a() {
    $var = "Hello World";
    $content = "";
    for ($i = 0; $i < 10000; $i++) {
        $content .= $var;
    }
    print '<br>$content size:'.strlen($content);
    print '<br>memory in function:'.memory_get_usage();
    return null;
}

print '<br>memory before function:'.memory_get_usage();
a();
print '<br>memory after function:'.memory_get_usage();

output:

memory before function:273312
$content size:110000
memory in function:383520
memory after function:273352

Before the function PHP used 273312 bytes.
Before the function was finished we checked the memory usage again and it used 383520.
We checked the size of $content which is 110000 bytes.
273312 + 110000 = 383312
The remaining 208 bytes are from other variables (we only counted $content)
After the function was finished we checked the memory usage again and it was back to (almost (40 bytes difference)) the same as it was before.

The 40 bytes difference are likely to be function declarations and the for loop declaration.

like image 179
Piotr Gajdowski Avatar answered Sep 21 '22 20:09

Piotr Gajdowski


You can see this example on a class, that's because you can "catch" freeing a variable in class' destructor:

class a {
  function __destruct(){
    echo "destructor<br>";
  }
}

function b(){ // test function
  $c=new a();
  echo 'exit from function b()<br>';
}

echo "before b()<br>";
b();
echo "after b()<br>";

die();

This script outputs:

before b()
exit from function b()
destructor
after b()

So it is now clear that variables are destroyed at function exit.

like image 41
Voitcus Avatar answered Sep 23 '22 20:09

Voitcus