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!
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.
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.
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 ([]).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With