A discussion came up at Digg today about the merits of arrays vs. stdClass instances. I’m generally in the stdClass camp, since I prefer the arrow syntax for accessing properties, and I was under the impression that there weren’t any other drawbacks. Boy, was I wrong.
I benchmarked performance of arrays vs stdClass instances. I started with stdClass, and I knew it was going to be bad. The code was run like so:
$ time php blah.php
And the times were generated by running this three times and averaging the duration.
For arrays: .778 seconds
For objects: 6.516 seconds.
Ouch! Eight times slower. Here’s the code:
<?php
for ($i = 0; $i < 1000000; $i++) {
$x = new stdClass;
$x->a = 'a';
$x->b = 'b';
}
?>
<?php
for ($i = 0; $i < 1000000; $i++) {
$x = array();
$x['a'] = 'a';
$x['b'] = 'b';
}
?>
The other thing is that there’s no object literal syntax in PHP like there is for arrays, so they can be less convenient. The array code is also slightly faster when using literal syntax: $x = array('a' => 'a', 'b' => 'b').
Discussion