[development] performance foo

Chris Johnson chris at tinpixel.com
Wed Dec 14 03:53:23 UTC 2005


Just came across something that triggered a bit of performance testing.  One 
can cast objects to arrays and vice-versa in PHP.

So, in common.inc, we have a function called object2array() that loops through 
  an object and makes it into an array.  Is that faster than the equivalent 
function using a cast (array) operator?  No.  In fact, it's about 2.4 times 
slower.  However, both are very fast for an object with 26 elements.  Here's 
the benchmark:

10000 'object2array' calls took 3.04 seconds.
The average was 0.00030442 seconds per call.

10000 'better' calls took 1.27 seconds.
The average was 0.00012693 seconds per call.


Here are the tested functions:

function object2array($object) {
   if (is_object($object)) {
     foreach ($object as $key => $value) {
       $array[$key] = $value;
     }
   }
   else {
     $array = $object;
   }
   return $array;
}

function better($object) {
     if (is_object($object)) {
         $array = (array) $object;
     }
     else {
         $array = $object;
     }
     return $array;
}


Worth a patch?


..chrisxj



More information about the development mailing list