tags:

views:

85

answers:

6

Does calling unset() free the memory that was associated with that object? There are a couple cases where I find myself handling large associative arrays and I would like to remove them when done (freeing up memory to create new ones).

+2  A: 

It doesn't free the memory immediately, but it allows the garbage collector to do it.

Daniel Egeberg
Can I call the garbage collector on demand or not?
Josh K
+6  A: 
Sarfraz
+4  A: 

unset() does "free" memory in php, but it lets the garbage collector decide when to actually release said memory. Thus, memory is freed on an as-needed or as-convenient basis (prior to PHP running out of available memory).

A major caveat is to watch that you're not attempting to unset() global variables within a local scope. Even variables passed in by reference will only have their local references unset when this is performed in a function's locale. To truly make memory available, any unset() should be done in that variable's appropriate scope.

sleepynate
+1 for comment on scope
Mark Baker
Yes. We'll not talk about how I became intimate with this minute detail. :P
sleepynate
A: 

In PHP >5.3.0, the gc_collect_cycles() function forces collection of any existing garbage cycles.

Mark Baker
+2  A: 

By unsetting a variable you're setting it's "refcount" to 0. This allows for the Zend Engine to shift things about in memory and it knows that it can overwrite your variables area in memory as it has a refcount of 0.

This occurs before garbage collection is even thought of. So there you have it, unset() does actually help you out during the lifecycle of your app.

Paul Dragoonis
Wrong. By unsetting, you decrementing the refcount of the variable -- more accurately, the refcount of the zval.
Artefacto
When referring to a "variable" it's implied a zval since that's the data structure of it. What I said was not wrong. ZE MM does what i described above.
Paul Dragoonis
+1  A: 

No, it doesn't necessarily free anything. It just decreases the reference count.

Example:

//object has reference count 1 because it has one variable referencing 1
$a = new BigObject;
//object still has reference count 2, but no new object was allocated in memory
$b = $a;
//object has reference count 1
unset($a);
//the object is still in memory

Nitpick corner: technically, there are two reference counts in play here -- the object's and the zval's. The reference count of the object is only 1 throughout the program, it's actually the reference count of the zval that's changed in the assignment and in the call to unset.

Artefacto