Reputation: 8721
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
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
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