Skip to content
Related Articles

Related Articles

Improve Article

Which one is better (unset() or $var = null) to free memory in PHP ?

  • Last Updated : 02 Jul, 2021

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.


    // Declare a variable and set
    // to some string
    $a = "hello geeks";
    echo "Before unset : $a";
    // Unset this variable
    echo "<br>";
    // Display the variable
    echo "After unset : $a";



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;



    // Declare a variable and
    // set to string
    $a = "Hello geeks";
    echo "Before null : $a";
    // Assign null to this variable
    $a = null;
    echo "<br>";
    // Display result
    echo "After null : $a";


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.

My Personal Notes arrow_drop_up
Recommended Articles
Page :