Pars
Pars

Reputation: 5262

Unset created variables or objects before returning in 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

Upvotes: 4

Views: 1509

Answers (1)

user3357118
user3357118

Reputation:

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.

Upvotes: 5

Related Questions