user1306322
user1306322

Reputation: 8721

Array of objects vs arrays of object's properties − which is more efficient?

Which is faster and consumes less memory — an array of objects with a set of properties or all of the object's properties as arrays?

I'm making a 2d tile game and the world consists of tiles, so I create a separate instance of Tile class for each tile, and some people say it could be faster if I used arrays of tiles' properties instead. I'd like to see the difference with my own eyes, but the game is too complex at this point to rewrite the code.

Update: I found some time to test both options, and with insignificant memory and cpu differences, array of objects wins for being so much easier to work with (code readability + debugging simplicity).

Upvotes: 1

Views: 458

Answers (2)

driis
driis

Reputation: 164301

It probably depends on your array creation and access patterns; but, as a rule of thumb, I would not expect those two approaches to have significant performance differences. If you really think it might be a performance issue, the only way to be sure is to implement both, profile the program, and compare results.

Having an array of Tile would likely be much simpler, straight-forward code, so go with that. If you have actual performance problems, profile to find the expensive sections of the code.

Upvotes: 3

shazeline
shazeline

Reputation: 503

From a memory usage standpoint, an array of properties will consume less memory. From a practical standpoint though, using the array of objects adds a layer of abstraction that allows for easier debugging and the ability to easily modify code to add in new properties.

Upvotes: 2

Related Questions