Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any benefit to unsetting an array before redeclaring it?

In your opinion, if I had an array of 100 000 entries of 8-character strings, would it be better for memory usage to unset($array) first and then redeclare it as $array = []; or to just directly redeclare it ($array = [];)?

Thanks!

like image 322
Anriëtte Myburgh Avatar asked Feb 02 '15 14:02

Anriëtte Myburgh


People also ask

How do you clear an array in PHP?

Method 1: unset() function: The unset() function is used to unset a specified variable or entire array. Parameters: $variable: This parameter is required, it is the variable that is needed to be unset.

Which points to the current element you're working with?

This internal pointer points to some element in that array which is called as the current element of the array. Usually, the current element is the first inserted element in the array.

How to access arrays in PHP?

Accessing Elements in a PHP Array The elements in a PHP numerical key type array are accessed by referencing the variable containing the array, followed by the index into array of the required element enclosed in square brackets ([]).


2 Answers

It all comes out the same. Overwriting the "old" array with ANYTHING new would cause the old array to (eventually) get garbage collected and removed from the system. Whether you do it in two stages:

unset($arr); // force delete old array
$arr = [];   // create new array

or just

$arr = []; // replace old array with new empty one

basically boils down the same thing: The old array will eventually get cleaned up.

like image 101
Marc B Avatar answered Oct 12 '22 22:10

Marc B


While Marc B's answer is absolutely correct, I wanted to see for myself based on Daan's comment.

Using memory_get_usage() I did a quick test between unset() and redeclaration. Both equally reduced memory.

unset()

$arr = array_fill(0, 1000000, 'abcdefgh'); // memory: 96613552
unset($arr);                               // memory:   224856

redeclaration

$arr = array_fill(0, 1000000, 'abcdefgh'); // memory: 96613552
$arr = [];                                 // memory:   224856
like image 21
Jason McCreary Avatar answered Oct 12 '22 21:10

Jason McCreary