We decided to do our map generator in Flash. One of the reasons was we can share the render code between game client and generator this way. We are planning on having really big maps in our game. To be on the safe side I quadrupled the requirements made by game design (well, you never know) and ended up with more than 10 million values to stuffed into memory. Each map position has different values such as terrain type, climate zone, humidity and height level, … so this is really a lot of data!
With such large data blocks I was facing three problems: One is data initialization time, another one is access time and the last one is memory footprint.
In the first iteration of my map-data class I used our extensive and comfortable dynamic property system. I thought it would be a good idea if I could add any amount of arbitrary data to any map entry. This freedom came with big price tag: It took forever to initialize and used about one Gigabyte of memory. This was absolutely not acceptable!
Consequently, this was not the way to go. Next, I tried a three-dimensional array. This approach makes the data a bit less flexible but it’s still ok. Initialization time was better but still not great. The memory footprint wasn’t what I would call good either. At least, I was now able to fit the data into memory (we’re still talking about over 100MB, though). To bring down initialization times I refactored the data class to use a linear array. Linear arrays are really fast to create, but then I realized that access times are terrible. So, I did not find a satisfying solution here either.
More or less by accident I stumbled over Flash’s built-in ByteArray class. It is basically works as a stream so I did not expect a great performance gain. I tried it anyway. Well, it really outperformed the three-dimensional array, which is astounding since the ByteArray needs the same offset calculations as the linear array does. The best thing about the ByteArray is it’s memory footprint. There is no class overhead and if you only need values between 0 and 255 (as I did) you can use one byte per value instead of wasting 4 bytes (size of int) each. This brought down the required memory to around 10 MB.
In my next post I will write about a little test suite I wrote to prove the power of the ByteArray. So stay tuned and remember to give ByteArray a chance.
Happy coding!
Popularity: 4% [?]
