# 2D array vs 1D array performance in C#

Is there performance difference between using 2D and 1D arrays?

I remember someone saying 1D arrays had better performance, but am not sure if it was true.

Has anyone done any tests, or know anything?

It’s true. 1D array > jagged array > 2D array.

–Eric

any stats on actual performance increase?

A 1D array is only a little faster than a jagged array, but both are somewhat faster than a 2D array. It’s easy enough to run a few benchmarks to see for yourself. Not worth worrying about unless you’re constantly accessing the array a lot, though; a 2D array is the simplest method for using a multi-D array so you should use that unless there’s a good reason otherwise.

–Eric

It depends on how many operations you are performing. In the below example, I’m setting the values of the array 2500 times. Size of the array is (1000 * 1000 * 3). The 1D array took 40 seconds and the 3D array took 1:39 mins.

var startTime = DateTime.Now;
Test1D(new byte[1000 * 1000 * 3]);
Console.WriteLine("Total Time taken 1d = " + (DateTime.Now - startTime));

startTime = DateTime.Now;
Test3D(new byte[1000,1000,3], 1000, 1000);
Console.WriteLine("Total Time taken 3D = " + (DateTime.Now - startTime));

public static void Test1D(byte[ ] array)
{
for (int c = 0; c < 2500; c++)
{
for (int i = 0; i < array.Length; i++)
{
array = 10;
}
}
}
public static void Test3D(byte[,] array, int w, int h)
{
for (int c = 0; c < 2500; c++)
{
for (int i = 0; i < h; i++)
{
for (int j = 0; j < w; j++)
{
array[i, j, 0] = 10;
array[i, j, 1] = 10;
array[i, j, 2] = 10;
}
}
}
}

Please use code tags when posting code.

–Eric