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.
Syntax:
unset($variable)
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.
PHP
<?php
$a = "hello geeks" ;
echo "Before unset : $a" ;
unset( $a );
echo "<br>" ;
echo "After unset : $a" ;
?>
|
Output:
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.
Syntax:
$variable = null;
Example:
PHP
<?php
$a = "Hello geeks" ;
echo "Before null : $a" ;
$a = null;
echo "<br>" ;
echo "After null : $a" ;
?>
|
Output:
Before null : Hello geeks
After null :
Which one is better?
unset() function:
- 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:
- 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.
Last Updated :
02 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...