Re: Manual unset and GC

From: Date: Mon, 10 Mar 2025 17:37:28 +0000
Subject: Re: Manual unset and GC
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-126697@lists.php.net to get a copy of this message
On 10 March 2025 16:15:16 GMT, Vinicius Dias <carlosv775@gmail.com> wrote: >Hello, folks. If this is not the correct place to ask, I apologize. > >> TL;DR: Does setting a variable to null (or even >> unseting it) have **any** effect if that's the last instruction >> of a function? > >The full version of the question with context: > >I have a question about the inner workings of PHP that was raised by >some people at work. > >In the code we write at the company I work for, there's a guideline to >always assign null to the variables of type >PdoStatement. >Something like the following: > >``` >$stm = null; >``` > >I understand this removes the reference to the object, calls the >destructor and frees the memory, but the point is: the guideline >mandates that we do that even if it is the last instruction of a >function, for example: > >``` >function example(): void >{ > // run your SQL queries > > $stm = null; >} >``` > >I understand that this last line is not needed and removing it would >have literally no effect on the code execution since $stm will >go >out of scope and the same things (remove reference, call destructor >and free memory) will happen exactly the same. > >While discussing this with a few colleagues it was pointed out that >**maybe** PHP will execute the GC immediately when we do $stm = >null >but not when the variable goes out of scope, making the explicit null >as some sort of optimization. > >I didn't find any resources on the documentation that could point to >which assumption is correct, so I post the question here: > >Does setting a variable to null (or even >unseting it) have **any** >effect if that's the last instruction of a function? > >Thank you No. It has no effect. At the end of the function PHP would remove a ref to the variable anyway. Setting it to null first is an action that will take time, unless opcache is turned on and realises it's a useless action. cheers Derick

« previous php.internals (#126697) next »