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!
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!
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