Adobe, MAKE SOME NOISE

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:

flat_array

(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.

  1. var myMDArray:Array = [
  2. ['0a', '0b', '0c', '0d', '0e'],
  3. ['1a', '1b', '1c', '1d', '1e'],
  4. ['2a', '2b', '2c', '2d', '2e']];
  5.  
  6. var myFlatArray:Array = ['0a', '0b', '0c', '0d', '0e', '1a', '1b', '1c', '1d', '1e', '2a', '2b', '2c', '2d', '2e'];
  7.  
  8. var columns:int = 5;
  9.  
  10. trace(myMDArray[2][4]);
  11. trace(myFlatArray[14]);
  12. trace(myFlatArray[(2 * columns) + 4]);
  13. // 2e, 2e, 2e

Now - supposing you have an index for something and want to reverse engineer the row and column - just break out the modulo grid code:

  1. var row:int = int(14 / columns);
  2. var col:int = 14 % columns;
  3.  
  4. trace(row, col);
  5. // 2, 4

3 Responses to “Flattening arrays”

  1. RodeoClown Says:

    Um, your RSS feed is full of spam again…
    Title is ok, the content is just ads for assorted drugs.

  2. Storage Says:

    Storage http://lregistryb0n.bestpartsstore.info/tag/scrapbook+solutions+Paper+Storage/ : scrapbook…

    Paper…

  3. Alexander Wang Jean Donna Hobo Says:

    Alexander Wang Jean Donna Hobo…

    We are constantly working to improve our products, services, and website to make your shopping experience at Top Brand Club a pleasant one. We wish you a pleasant shopping!…

Leave a Reply