6

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!

Anriëtte Myburgh
  • 13,347
  • 11
  • 51
  • 72

2 Answers2

8

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.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    Someone made a interesting benchmark to see it in real, that I found by pure chance looking for `memory_get_usage` and which I found really eye opening on this exact matter and on garbage collection in PHP in a larger scope and it can be found here http://www.tuxradar.com/practicalphp/18/1/11 – β.εηοιτ.βε Feb 02 '15 at 14:55
  • to be expected. garbage collection is expensive. php isn't going to do unless it has to - e.g. you requested more memory than is available in the "free" pool, or you manually trigger the GC system. – Marc B Feb 02 '15 at 14:56
  • I did a quick Gist https://gist.github.com/AnrietteC/d9245343fe8e856da30e , and it seems that although memory usage is parallel between unsetting or just redeclaring, execution time is faster without unsetting. It seems unset() really only has a benefit if you are not re-using the variable. – Anriëtte Myburgh Feb 02 '15 at 15:17
3

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
Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174