Thursday, July 2, 2009

Array vs Class - which is better?

The other day I was discussing with my friend and we talked about Array and Classes. of course in Samstyle PHP Framework, I actually dropped the usage of classes. There are reasons why I went for arrays instead of classes.

With the help of PHP: Arrays vs. Objects - 't Bijstere spoor (http://www.rooftopsolutions.nl/article/148), I actually wrote a piece of code that tests for memory usage of Array and Class.

For Array memory testing:
$data = array();
echo memory_get_usage().' b<br/>';

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

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

}
echo memory_get_usage().' b<br/>';


The memory usage difference was 549064 bytes for using Arrays.

For Class memory testing:
class Test {

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

}

echo memory_get_usage().' b<br/>';

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

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

}
echo memory_get_usage().' b<br/>';


The memory usage difference was 573224 bytes for using Classes.

Arrays actually has a less memory usage (549064 bytes to create 1000 arrays) compared to Classes (573224 bytes to create 1000 classes).

Well, in terms of speed, we did the same thing, except measuring time. Arrays (0.0161869525909s to loop 1000 times) are actually faster compared to classes (0.0189130306244s to loop 1000 times).

Therefore in terms of speed and performance, Arrays won over Classes.

On top of that, Arrays allows you to use the FOREACH($ARR as $KEY => $VALUE) loop, which is easier and better for us programmer, instead of statically writing each property of the class.

However, Arrays do not support instances, unlike Classes. Classes can define methods which allows the code to look cleaner and more efficient.

Note that the timings taken are an average of 5 runs spreaded across 5 mins (i.e. 1 run per minute) for the most accurate timings. Please note that the timings may differ from computer to computer. I am using Intel QuadCore 2.4GHz, 4GB RAM, Windows XP SP3, XAMPP 1.7.1, PHP 5.2.9.

1 comment:

Πετσαγγουράκης Γιώργος said...

You might want to check out the Predifined Interfaces of PHP. They allow for accessing a class like an array and some more stuff.