views:

421

answers:

3

I have a huge amount of PHP objects for a neural network for which I have to iterate over and perform some maths on. I was wondering if I would be better off using an associative array over instances of classes?

I am dealing with around 3640 objects and iterating around 500 times (at best) on top of that so any micro-optimization helps a great deal. Would it inevitably be quicker to do $object['value'] than $object->value?

Edit: So they are both the same. But I guess there would be a little overhead for the constructor? Either way I don't think I want to trade in my beautiful classes for dirty arrays :P

+1  A: 

You can always check the PHP-source code for micro-performance-features like that.

But at a first glance, no doing ['value'] will not be faster because PHP needs to do a Lookup on where to find ['value'] even thougn a hashtable lookup should be O(1), that's not guaranteed. There's more overhead when you use Text-index.

If the object only contains 1 variables that you need to access which is value, there's more overhead in using an object.

Filip Ekberg
And where do you think properties are looked up? They're in a hash table, too... (though this is only more or less true in trunk).
Artefacto
+1  A: 

You haven't shown us the code for how $object->value works, as it could be that backend it is an array in which case theoretically using an array would be faster as it involves one less function call. The cost of doing the lookup will probably be huge compared to the function call. If it is a variable, there is going to be very little diffrence as objects and arrays in PHP have a very similar implementation.

If you are looking at optimizations, you will need to profile to check where the majority of the time is being used. I suspect that changing objects to arrays will make no major difference.

Yacoby
I assumed that value would be a public variable, therefore defenitely O(1) while the hash-lookup might not be.
Filip Ekberg
+3  A: 

If you're using PHP5 then difference between objects or arrays almost is not significant. Here one man makes some performance testing for the best data structures: http://aggregation.novaak.net/?q=node/227.

Sergey Kuznetsov
PHP5 may be more efficient, but your own benchmarks show objects are 50% slower, and that's still ignoring the memory usage too, which is pretty bad in PHP for objects. IMHO this is very significant. You do realize 3640 * 500 = 1.8 million iterations, so I'd prefer the lighter solution.
TravisO