What’s better at freeing memory with PHP: unset() or $var = null?

Technology CommunityCategory: PHPWhat’s better at freeing memory with PHP: unset() or $var = null?
VietMX Staff asked 3 years ago
  • unset() does just what its name says – unset a variable. It does not force immediate memory freeing. PHP’s garbage collector will do it when it see fits – by intention as soon, as those CPU cycles aren’t needed anyway, or as late as before the script would run out of memory, whatever occurs first.
  • If you are doing $whatever = null; then you are rewriting variable’s data. You might get memory freed/shrunk faster, but it may steal CPU cycles from the code that truly needs them sooner, resulting in a longer overall execution time.

unset($a)also removes $a from the symbol table and it seems that $a = null is a bit faster than it’s unset()counterpart: updating a symbol table entry appears to be faster than removing it.