Flattening arrays
September 21st, 2009
A big danger when working with large sets of data is the possibility of introducing a small slowdown that's compounded with every piece of data in the set. A common example is the multidimensional array; it's a powerful tool, but every time you look into the array you have to go at least two lookups deep to find your data. Normally that's not a big deal but if you're touching the set thousands of times per frame, it adds up quickly.
A fairly drastic solution is to flatten your arrays - it will give you a nice performance boost when you access the data, but it comes at the cost of obfuscation. Here's how it works:

(Sorry the numbers are goofy between the diagram and the code - CS4 crashed and I didn't feel like re-making that graphic)
In the traditional 2D view each "row" is a new Array object - this is where the added computing cost comes in. By flattening the data into one super-long array, you can access any piece of data with just one lookup. Finding the correct cell is a little more tricky though.
Now - supposing you have an index for something and want to reverse engineer the row and column - just break out the modulo grid code:
