Skip to main content
IBM  
Shop Support Downloads
IBM Home Products Consulting Industries News About IBM
IBM developerWorks : Web Architecture : Education - Tutorials
Writing efficient PHP
ZIPPDF (letter)PDF (A4)e-mail
Main menuSection menuFeedbackPreviousNext
2. Writing efficient code
  


Optimizing loops: create or destroy objects page 6 of 15


Although PHP is not a fully object-oriented language, it does support the concept of objects. As with any language that supports object creation, a small overhead is associated with creating a new instance of an object, as well as with destroying an object. Therefore, create and destroy objects within a loop only when necessary.

Often, you can create an object outside of the loop. Then you can either treat it as read-only within the loop or, if different object settings are required in each iteration, modify its properties instead of destroying one object and creating a new one. For example:


for ( $i=0; $i<$arraySize; ++$i )
   {
   $pt = new Point( $i, $myArray[$i] );
   // do something with $pt
   }

In this case, assume a Point object has two properties of interest: x and y. In each iteration of the loop, a new Point object is created (with the new keyword) and destroyed. As an alternative, you can create one instance before the loop and then modify its properties in each iteration. This removes the overhead of destroying the old instance and creating a new one. The code would be as follows:


$pt = new Point();
for ( $i=0; $i<$arraySize; ++$i )
   {
   $pt->x = $i;
   $pt->y = $myArray[$i];

   // do something with $pt  
   }

Note that because in PHP all of an object's member variables are public, this type of optimization should usually be possible. It may not always be desirable from a pure object-oriented design perspective, but that tradeoff is up to you as the developer.


Main menuSection menuFeedbackPreviousNext
Privacy Legal Contact