Skip to content

Latest commit

 

History

History
82 lines (57 loc) · 2.45 KB

2007-08-16-148.md

File metadata and controls

82 lines (57 loc) · 2.45 KB
date layout slug title tags location geo
2007-08-16 04:33:40 UTC
post
148
PHP: Arrays vs. Objects
php
array
object
vo
valueobject
benchmark
Toronto, Canada
43.635695
-79.424994

In a lot of cases arrays are used in PHP to store object-like information, like the results of a database query. I do this a lot too, but I kind of want to change things around to make use of VO's. I feel this makes a lot more sense, since most of the application I build are heavy OOP anyway, and I get all the added OOP benefits, like type-hinting, inheritance.. well, you know the deal.

I wanted to see what the differences would be in terms of memory consumption, so I set up the following test:

<?php

   // first test simple associative arrays
   $memory1 = xdebug_memory_usage( );

   $data = array();

   for($i=0;$i<1000;$i++) {

       $data[] = array(
            'property1' => md5(microtime()),
            'property2' => md5(microtime()),
            'property3' => md5(microtime()),
       );

   }

   $array =  xdebug_memory_usage()-$memory1 . "\n";

   // Now do the same thing, but with a class..

   class Test {

       public $property1;
       public $property2;
       public $property3;

   }

   $data = array();

   $memory1 = xdebug_memory_usage( );

   for($i=0;$i<1000;$i++) {

       $test = new Test();
       $test->property1 = md5(microtime());
       $test->property2 = md5(microtime());
       $test->property3 = md5(microtime());
       $data[] = $test;


   }

   $object = xdebug_memory_usage()-$memory1;

   echo 'Arrays: ' . $array . "\n";
   echo 'Objects: ' . $object;

?>

My results were

Arrays: 536596
Objects: 521932

I knew there was a good chance objects would take up less memory, because arrays need to store both the propertyname (or key) and value for every record, while the object only needs to store the values, because the propertynames are stored centrally in the class definition, what I didn't expect was that using arrays takes more than 20 times more memory. This is hardly an accurate formula, but it does tell you something.

Right, that was stupid.. I had my testing code wrong and I did the $data=array(); right after the second xdebug_memory_usage(). The actual conclusion here is that there's not much difference. I was hoping the objects would make a significant difference, but its minimal.