Kalreg
Kalreg

Reputation: 941

php - array or objects to store data - what is better solution

I am just thinking what would give me better perfomance and memory usage. I am programming a map for a game. Everything is stored in class "map" but a map may have thousands of tiles. Now i am thinking what is better solution:

Because I may have thousands of similiar tiles first impression would be that it is best for oop programming, but i am afraid that thousands of object tiles might use much more memory and calling to it's methods might be slower. What do you think about it?

Kalreg

Upvotes: 3

Views: 2647

Answers (3)

Naeem Ul Wahhab
Naeem Ul Wahhab

Reputation: 2495

It depends on the php version you are using. If the version you are using is PHP5 or above(which you should as latest php version will mean more performance for your game app) then using both arrays and objects will give almost same performance for your application. So if you are-using/can-use PHP 5 or above then you may use arrays or objects according to your convenience.

Check this array vs object comparison/tests by Aron Novak: http://aggregation.novaak.net/?q=node/227. I am quoting it bellow in Aron Novaks words:

I created a small script to find out which data structure has better performance. You can find the script what I used for the test at the attachments.
My test results are:
    data structure          PHP4        PHP5
    object                  61.6224     37.576
    array                   57.6644     37.866

    The results are in milliseconds(ms). It seems that in PHP5 the data structure is totally indifferent, in PHP4 there is approximately 7% performance gain if use arrays instead of objects.
    "This revolution, however, left PHP's object model mostly unchanged from version 3 – it was still very simple. Objects were still very much syntactic sugar for associative arrays, and didn't offer users too many features on top of that." (http://devzone.zend.com/node/view/id/1717)
    So the syntactic sugar is not a bad thing at all :) And it costs almost nothing. This is an explanation why all the parsers' output uses objects.

Check this http://we-love-php.blogspot.com/2012/06/php-memory-consumption-with-arrays.html for a detailed/great article on PHP arrays vs objects memory Usage and Performance

Upvotes: 4

Baba
Baba

Reputation: 95101

You are developing a game definitely you can not use only array or objects you are mostly likely to use both.

I think you should first understand How big are PHP arrays (and values) really? (Hint: BIG!)

Replace your array with SplFixedArray and store your objects in SplObjectStorage you should get improvements in your code.

Upvotes: 1

Rob Cozzens
Rob Cozzens

Reputation: 136

If you have a grid of tiles, that lends itself really well to being stored in an array.

But if those tiles have a lot of information attached to them, that lends itself to objects.

I would suggest an array of objects.

Upvotes: 0

Related Questions