Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unset created variables or objects before returning in php

Tags:

php

In terms of Memory Optimization, if there are too many requests to server, is there any difference between these two scripts:

public function func1(){
    $user = new User::find(10);
    $name = $user->name;
    return $name;
}


public function func2(){
    $user = new User::find(10);
    $name = $user->name;
    unset($user);
    return $name;
}

if yes, could you please explain why.

AND, won't PHP itself unset variables while exiting a function or method ?

thanks in advance

like image 356
Pars Avatar asked Aug 30 '25 18:08

Pars


1 Answers

The accepted answer to questions-about-php-unset-function and the article better-understanding-phps-garbage-collection indicate that garbage collection occurs when the function returns, so memory used by the local variables is automatically freed on return. Therefore explicitly calling unset just prior to return does not appear to provide a memory optimization.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!