1

I have a class, which (among other things) contains a simple array of objects instanced from another class. (This array is small - containing only 1 to perhaps 4 objects.)

In the __destruct method of the first class I want to clear the contents (free the memory) of this array of objects. In order to do this, do I:

  1. iterate through the array, setting each index = null, then finally setting the array = null?

  2. simply set the array = null?

  • 3
    use `unset($array);` – splash58 Jun 24 '16 at 17:37
  • Related: http://stackoverflow.com/questions/584960/whats-better-at-freeing-memory-with-php-unset-or-var-null but either way, there's no reason to do this on the individual elements of the array. Just null/unset the whole thing. – rjdown Jun 24 '16 at 17:42

2 Answers2

0

As already mentioned by @splash58 you can use unset to delete a variable.

unset($array); // can be used on multiple as well: unset($var1, $var2, ...);

Unset will simply destroy the variable.

codedge
  • 4,754
  • 2
  • 22
  • 38
0

Re: rjdown link. Thanks. I had previously read that question/answers.

From that post I concluded (perhaps incorrectly) that there appeared to be 2 (possible?) differences between unset($var) and $var = null.

  1. the speed at which the memory is actually released. ($var = null appeared to be faster.)

  2. the processing load of the method. (unset($var) appeared to present less of a load.)

For reasons, I decided on speed of memory release, and thus went with the use of the null assignment.

However, the question remained - the array would be null, but would the objects previously contained by the array be non-null and thus have to wait around for GC?

Since a test was actually easy to do, I did it.

I created about 1,000 child records for a parent class. Then I instanced a new parent class and loaded the 1,000 child objects into the array.

I used memory_get_usage() in a test file, and ran a number of trials where:

  1. the parent class' __destruct method simply unset the array of child objects.

  2. the parent class' __destruct method iterated through the array, setting each instance = null, then unset the array.

Data as follows:

  • using parent __destruct unset array

Start memory - 620288

memory after parent instanced and child array loaded - 1316952

memory after parent set to null - 620864

mem diff = 576

  • using parent __destruct iterate array = null

Start memory - 620952

memory after parent instanced and child array loaded - 1317616

memory after parent set to null - 621528

mem diff = 576

(I also put a microtime interval across parent object creation, child array load, parent object destruction. Tests for each of the 2 __destruct methods were essentially equivalent at around 10 ms.)

From this I conclude - there really isn't much of a difference. Unset or null, whatever floats your boat.

(Perhaps I should have simply run my own tests prior to bothering the forum with a question.)

Again, thanks.