0

I have a 3D data array which represents a stack of 2D data. In this particular case, the stack only contains one element. What is the fastest way to map this data to a linear array?

I was planning to take the following approach:

public static int[] ToBuffer<(this int[, ,] buffer3D, int w, int h)
  {
      int[] buffer = new int[w * h * 1];

      for (int i = 0; i < (w * h); i++)
      {
          buffer[i] = buffer3D[(int)Math.Floor(i / (double)w), i % w, 0];
      }

      return buffer;
   }

But it occurred to me that there might be some way to take advantage of how the data is already stored in memory. Is there some other mapping approach that should be employed in csharp?

dionys
  • 151
  • 8

2 Answers2

1

While you could potentially use some Linq here, the .ToArray() function internally uses an array with a set size, and then replaces it when it gets too big - not ass efficient as the code already posted. (See: class Enumerable on Reference Source)

Note that C#s primary advantage, memory management, is also its primary downfall for optimizations like this - since pointers and the like are highly managed, accessing them in such a way to optimize code like this is often far more difficult in C# than other languages.

David
  • 10,458
  • 1
  • 28
  • 40
1

I guess, creating new buffer for the new array and copying the buffer of the 3d-array should work:

public static int[] ToBuffer(int[, ,] buffer3D, int w, int h) {
    int[] buffer = new int[w * h * 1];
    Buffer.BlockCopy(buffer3D, 0, buffer, 0, w * h * sizeof(int));
    return buffer;
}
Batuhan Tasdoven
  • 798
  • 7
  • 19