php - When unset() should really be used? -


i'm curious using of unset() language construct everywhere, took memory or declare variables (regardless of structure).

i mean, when declares variable, when should left gc, or unset()?


example 1:

<?php $buffer = array(/* on 1000 elements  */);  // 1) long code, uses $buffer  // 2) long code, not use $buffer ?> 
  1. is there chance, $buffer might affect performance of point 2?
  2. am need (or should) unset($buffer) before entering point 2?

example 2:

<?php function somefunc(/* args */){     $buffer = new verylargeobject();      // 1) actions $buffer methods , properties      // 2) actions without usage of $buffer      return $something; } ?> 
  1. am need (or should) unset($buffer) within somefunc()s body before entering point 2?
  2. will gc free allocated memory (references , objects included) within somefunc()s scope, when function come end or find return statement?

i'm interested in technical explaination, code style suggestions welcome too.

thanks.

in php, memory gets cleaned after script finished, , of time it's enough.

from php.net:

unset() it's name says - unset variable. not force immediate memory freeing. php's garbage collector when see fits - intention soon, cpu cycles aren't needed anyway, or late before script run out of memory, whatever occurs first.

if doing $whatever = null; rewriting variable's data. might memory freed / shrunk faster, may steal cpu cycles code needs them sooner, resulting in longer overall execution time.

in reality use unset() cleaning memory pretty rare, , it's described in post: https://stackoverflow.com/a/2617786/1870446

by doing unset() on variable, mark variable being "garbage collected" memory isn't available. variable not have data anymore, stack remains @ larger size.
in php >= 5.3.0, can call gc_collect_cycles() force gc pass. (after doing gc_enable() first).
must understand php script language, it's not java shouldn't consider one. if script heavy use tons of ram - can use unset , when script close exceed memory - gc trigger , clean useless, including unset variables. in cases can forget it.
also, if want go unsetting every variable not use - don't. make script execute longer - using more cpu cycles - sake of getting free memory would, in cases, never needed.
people use unset explicitly show won't use variable anymore. find bad practice too, me makes code more verbose these useless unsets.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -