Which one is better (unset() or $var = null) to free memory in PHP ?
In this article, we will discuss freeing the memory with unset() and using NULL value to any variable.
unset(): The unset() function is an inbuilt function in PHP that is used to unset a specified variable. The unset() function just destroys or removes the variable from the symbol table. After the unset() applied on a variable, it’s marked for PHP garbage collection.
- $variable which is unset
Example: The following example demonstrates the unset() function. In the following example, the $a memory is removed from the variable stack, the $a does not exist anymore after the unset action.
Before unset : hello geeks After unset :
null: null is used to empty the variable. We can create a null variable by simply assigning it to null. The memory is not freed, but NULL data is re-written or re-assigned on that particular variable.
$variable = null;
Before null : Hello geeks After null :
Which one is better?
- unset() does not force immediate memory freeing, and it is used to free variable usage.
- PHP garbage collector cleans up the unset variables.
- CPU cycles are not wasted
- It takes time to free memory
- null variable immediately frees the memory.
- CPU cycles are wasted and it takes longer execution time.
- It speedily frees the memory.
Conclusion: NULL is better if the memory needed is less for a variable.