Brandon Savage takes issue with my post benchmarking objects and arrays.
His argument is a straw man. My post is about a specific application – simple, flat data, where the primary concern is ease of syntax for accessing that data. He generalizes that position into one of OOP vs. non-OOP, which is not even remotely close to what I wrote.
So, let me be clear. OOP is, generally, good. His tips on writing OOP code are also generally good. In fact, I wrote a class to make dependency injection painless. Other paradigms, like functional programming, are also good.
This is not about that. This is about what’s faster for simple data storage: arrays or stdClass instances. The answer was, and still is, arrays.
I took the code from the previous post and re-ran it against PHP 5.3.0 on Snow Leopard. Everything else is is the same as in the other test. I added two new measures. One using $x = array('a' => 'a', 'b' => 'b'), and one with an object class with a constructor, like so:
class AnObject
{
public $a;
public $b;
public function __construct($a, $b)
{
$this->a = $a;
$this->b = $b;
}
}
Here are the results:
| Method | Time (in seconds) |
|---|---|
| Arrays (create, then assign) | .6226 |
| Arrays (literal syntax) | .5346 |
| Objects (create, then assign) | 1.01 |
| Objects (assign in constructor) | 1.4354 |
As you can see, things are better than in PHP 5.2, but arrays are still faster in every case.