Thursday, September 17, 2009

Start with simple foreach optimization

We used most of the time PHP array to save code information, objects, list.
Most of the time we used foreach loop to read array values but i want share one simple optimization in that foreach.
I wrote bigger script for fixing bugs in my applications.
My applications contains many databas connections and many rows and i am using the objects so most of the time my script was failing because of the memory execution issue.
The simple optimization i had done with PHP foreach loop.
Previously i was using like this:
$array_of_objects = $object->getList();// contains may records more then 10000.
if(count($array_of_objects)>0)
{
foreach($array_of_objects as $key=>$object)
{
// the object processing
}
}

======= Optimized code=======
$array_of_objects = $object->getList();// contains may records more then 10000.
$size_of_objects = sizeof($array_of_objects);
if($size_of_objects>0)
{
for(i=0;i<$size_of_objects;$i++)
{
$object =&
$array_of_objects[$i];
}
}
======= Optimized code=======

=======Why i used For=======
basically foreach loop copying the array of objects but in for loop i am using array of objects using
as reference it will save memory.
=======Why i used For=======

No comments:

Post a Comment