0

What's the best way (if possible?) to create an 3D array (e.g myArray[x][y][z]) with underlying ArrayBuffers. The array should consist of Uint32Arrays.

In my case it's a rather large array (about 200x200x200). Iterating over it would be much faster if I use typed arrays such as uint32 I guess, hence I would like to use ArrayBuffers. Or am I wrong?

2
  • Are you saying you want a 3D array in which each element is a Uint32Array or do you want a 3D ArrayBuffer? Commented May 19, 2016 at 20:19
  • I want a 3D ArrayBuffer. Each value in the array will be a uint32. That is, myArray[x][y][z] = int32Value; Commented May 19, 2016 at 20:33

1 Answer 1

1

You can write a simple function that converts x/y/z indexes into the corresponding index into the ArrayBuffer.

function arrayIndex(x, y, z, xSize, ySize) {
    return z + ySize * (y + x * xSize);
}

See Memory layout of multi-dimensional arrays for the general algorithm to convert a set of indexes into the linear index.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, I'm aware of that. But I've benchmarked using flattened array using ArrayBuffers compared to just a 3D array and the latter was faster to iterate over in Javascript (which was the opposite of what I thought). Hence, I thought if it was possible to use ArrayBuffers without flatten the 3D array to 1D.
Do you need to do random access into the ArrayBuffer, or just iterate through the whole thing?
I would need both random access and iteration. So I need to access it like myarray[x][y][z] and also iterate over the whole structure. An alternative way would be to use flattened arrays but perhaps use some memory layout that increase iteration performance (morton encoding?). When I tried iteration over my flattened array I did like this: pastebin.com/r38NdJaP . Perhaps you have a better idea? My arrays are symmetrical.
That pastebin is pretty much what I envisioned to optimize iteration. There isn't really any way to optimize random access. Real arrays are more efficient because the indexing is in compiled code in the JS engine. So you have to choose between CPU and memory efficiency.
Another possible compromise is a 2-D array of ArrayBuffers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.