Really Damn Slow: A look at PHP objects

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').

2009/02/27
Previously On Atomized:

Discussion

On which PHP Version did you measure that?
On a PHP 5.2.3 I measured 5.35s for array and 7.81s for object. Although I was using 5000000 loops.

Mathias
2009/05/04

That was measured on PHP 5.2.6, as shipped with OS X 10.5.6.

Ian
2009/05/04

[...] such a good point. There seems to be a perception in the PHP world that using lots of objects is slow, cumbersome, or plain difficult to maintain. But the reality is that this is not true at all (for example the object model in PHP 5.3 is vastly [...]

Five Tips To Make Good Object-Oriented Code Better | BrandonSavage.net
2009/10/27

[...] such a good point. There seems to be a perception in the PHP world that using lots of objects is slow, cumbersome, or plain difficult to maintain. But the reality is that this is not true at all (for example the object model in PHP 5.3 is vastly [...]

Five Tips To Make Good Object-Oriented Code Better » Koolphp.cn
2009/11/18

If you could remove the flashing background and change the text color to black, it will be easy to read…

George
2010/01/15

@George, What are you talking about? The text is black, and the background doesn’t flash.

Perhaps your browser is just incapable of correctly rendering my layout.

Ian
2010/01/15

Classes are not 8 times slower than arrays.
I have done extensive tests on comparing these and classes are only 5-10% slower.

Classes are easier in use than arrays in some cases, I find the readability a lot better with classes.

Also, why not just use $x = ”; to create the object?!

Peter van Westen
2010/02/24

If you could rwmove the tlashing background and chanve the text color to black, it will be easy to read…;

Azatyan
2010/03/11

I’m sorry, I have absolutely no idea what you’re talking about.

Ian
2010/03/12

Participate