Search code examples
c++arraysdata-structuresdynamic-memory-allocation

Dynamically allocate or waste memory?


I have a 2d integer array used for a tile map.

The size of the map is unknown and read in from a file at runtime. currently the biggest file is 2500 items(50x50 grid).

I have a working method of dynamic memory allocation from an earlier question but people keep saying that it a bad idea so I have been thinking whether or not to just use a big array and not fill it all up when using a smaller map.

Do people know of any pros or cons to either solution ? any advice or personal opinions welcome.

c++ btw

edit: all the maps are made by me so I can pick a max size.


Solution

  • My preference would be to dynamically allocate. That way should you encounter a surprisingly large map you (hopefully) won't overflow if you've written it correctly, whereas with the fixed size your only option is to return an error and fail.

    Presumably loading tile maps is a pretty infrequent operation. I'd be willing to bet too that you can't even measure a meaningful difference in speed between the two. Unless there is a measurable performance reduction, or you're actually hitting something else which is causing you problems the static sized one seems like a premature optimisation and is asking for trouble later on.