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?

3
  • Can you try return (int[]) buffer3D.Clone(); ? Commented Nov 2, 2014 at 23:37
  • Possible duplicate stackoverflow.com/q/4674394/395718 Commented Nov 2, 2014 at 23:43
  • @BatuhanTasdoven No, unfortunately this results in an InvalidCastException: Unable to cast object of type 'System.Int[,,]' to type 'System.Int[]'. Commented Nov 3, 2014 at 0:04

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.