Tuesday, October 4, 2011

When unset() is bad in PHP

Many of my developers that work with and for me love the unset() function which is a really good thing, but there is one spot I noticed that they tend to put it that may not be such a good idea.  What I am talking about is usetting the iterator in a foreach loop like so:

foreach($myarray as $value) {
    echo $value."\n";
    unset($value);
}

The reason this is bad is because of how PHP works internally.  When PHP iterates through the array it reuses the iterator variable ($value) and the memory with it.  Whereas if you unset it, each time PHP has to work to free that memory and then reallocate new memory for the next iteration.  As you can see it is not a good idea.

No comments:

Post a Comment