Is flattening JavaScript 2D arrays worth any performance gain?

arrays, javascript, multidimensional-array, performance

Solution

1D array may have a performance benefit due to the index look-up times. A 2D+ array will first have to have one index looked up, then in the resulting array yet another and so forth. There is an initial cost each time but it may be microscopic all in all.

If you really want a gain in performance then consider using Typed Arrays. These are actual low-level byte arrays and you can use them with 8-bit, 16-bit, 32-bit and 32/64 bits float values, signed and unsigned (latter not for float).

If your numbers are of one type then you can use typed arrays. You use them as any other array with index look-up but performance can be many times as these are optimized by the JS engine(s):

var array = new Uint8Array(9);  // 9 x bit-width, here 8 = 9 bytes

// write
array[0] = 1;
array[1] = 2;
...etc.

// read
var value1 = array[0];
...etc.

Problem

As far as I know, there are two main ways of storing 2D data. One, a 2D array: ``` var array = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // access element at (1, 1) array[1][1]; ``` The other, a flat array with a stored `width`: ``` var array = [1, 2, 3, 4, 5, 6, 7, 8, 9]; var width = 3; // access element at (1, 1) array[1 * width + 1]; ``` It's being said all over the Internet that "multidimensional" arrays are bad and perform super poorly compared to flat arrays and storing the width. (Also, typed arrays can be used to speed up the second variant even more). However, I really dislike the syntax you must use to access a point with the flat array, and I think that you should code as close to what you mean. Also, it's a lot of (I think) unnecessary math every frame. I'm in a situation where I need to handle large 2D arrays quickly (you guessed it, a game) and I want to know if flattening my arrays is worth the possible performance gain. So, is it?

Original source