Thursday, May 6, 2010

Retention of Object Instances in a Loop That's No Longer Needed is a Serious Flaw

The topic itself is self explanatory and normally, this should be taken care of by common sense. But not all developers are like that and they tend to just test against functionality. So, for those who doesn't consider this as a matter of great importance in writing code, let me illustrate it for you.

Take a look at the following code,



for($i = 0; $i < 50; $i++) {
$instance[$i] = new SomeClass();
//do something with $instance[$i];
}

This is a common quirk for PHP developers relying too much on PHP's built-in garbage collector. But as you can see if the instantiated class is too big, it will rapidly consume your memory limit and cause the application to crash.

Anyway, the fix is simple. Just destroy the object for every iteration.

for($i = 0; $i < 50; $i++) {
$instance[$i] = new SomeClass();
//do something with $instance[$i];
unset($instance[$i]);
}
  • Related Links Widget for Blogspot

No comments: