Is there any use to discarding an array before reusing it?

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

Thanks!

+6
source share
2 answers

Everything goes the same. Overwriting the “old” array with NOTHING new will cause the old array (eventually) to receive garbage collected and removed from the system. Do you do this in two steps:

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

or simply

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

basically comes down to the same thing: the old array will eventually be cleared.

+8
source

While Marc B's answer is absolutely right, I would like to make sure of myself based on Daan's comment.

Using memory_get_usage() I quickly checked between unset() and re-declaration. Both equally reduced memory.

unset()

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

redefinition

 $arr = array_fill(0, 1000000, 'abcdefgh'); // memory: 96613552 $arr = []; // memory: 224856 
+3
source

Source: https://habr.com/ru/post/981874/


All Articles