Does PHP free local variables immediately after the function ends?

后端 未结 4 1981
迷失自我
迷失自我 2020-12-19 03:59

The code illustrates better what I\'m asking:

function foo(){

  $var = get_huge_amount_of_data();

  return $var[0];
}


$s = foo();

// is memory freed her         


        
相关标签:
4条回答
  • 2020-12-19 04:39

    Yes it is because $var is declare on stack and get clear as soon it goes out of scope

    You can refer this https://stackoverflow.com/a/5971224/307157

    0 讨论(0)
  • 2020-12-19 04:41

    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.

    0 讨论(0)
  • 2020-12-19 04:43

    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.

    0 讨论(0)
  • 2020-12-19 04:50

    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?

    Yes, PHP makes a good job. This is a question you should never need to think about. In your case I would rather think about the moment between $var = .. and return .., because that is the moment, where you cannot avoid the memory consumption. You should try to find a solution, where you don't need to fetch the whole dataset via get_huge_amount_of_data() and then select a single item, but only the data you need.

    0 讨论(0)
提交回复
热议问题