-1
public static Vector2[] To1DArray(this Vector2[,] grid)
{
    Vector2[] array = new Vector2[grid.Length];
    for (int i = 0; i < grid.GetLength(0); i++)
    {
        for (int j = 0; j < grid.GetLength(1); j++)
        {
            array[grid.GetLength(1) * i + j] = grid[i,j];
        }
    }
    return array;
}

I'm talking about that array of Vector2 struct I created in the first line of the function.

Hermit Cat
  • 7
  • 1
  • 1
  • The array itself lands on the heap in every case: https://stackoverflow.com/questions/1113819/arrays-heap-and-stack-and-value-types Whether the garbage collector is smart enough to reliably remove it as soon as the reference goes out of scope, is a good question. – AlexGeorg Jul 22 '21 at 12:31
  • 2
    [The Stack Is An Implementation Detail](https://learn.microsoft.com/en-us/archive/blogs/ericlippert/the-stack-is-an-implementation-detail-part-one), you shouldn't care. Current implementations of CLR always store arrays (and any reference-type) on the heap, not stack. You can shorten the copying code with `Buffer.BlockCopy(grid, 0, array, 0, array.Length);` – Charlieface Jul 22 '21 at 14:11

2 Answers2

0

You are returning that array. That means the reference is being returned and thus the array will definitely not be garbage collected. Unless you use the "unsafe mode", C# will never free memory you have a reference to etc. (unlike C++ if you use it wrong).

In my comment above, I thought your question was related to performance with arrays that are on purpose supposed to exist exclusively within one function only. Your function is safe to use however.

AlexGeorg
  • 967
  • 1
  • 7
  • 16
  • ooh I'm creating the instance of my grid array and just returning the reference to that instance. that makes so much sense. thank you! – Hermit Cat Jul 23 '21 at 09:51
0

Arrays go on the heap.

But in general you shouldn't worry too much about that.

If you really do you should look into "Array Pooling". Especially if your grid always has the same size.

Btw under the hood both arrays are stored linear in the memory.

You could simply use Buffer.BlockCopy

var array = new Vector2[grid.Length];
Buffer.BlockCopy(grid, 0, array, 0, grid.Length * 2 * sizeof(float));
return array;

to convert between them.

derHugo
  • 83,094
  • 9
  • 75
  • 115