It's dangerous to code alone! Take this.

Performance of 2D Arrays

Published on 31 Oct 2022.

Whenever I do some performance profiling, I like to write up what I saw and share it. That’s what this is.

If you need to represent 2D data in a grid, there are three ways to do it. First, you can use a 2D array:

 int[,] array2D = new int[100, 100];

Second, you can use a jagged array:

 int[][] arrayJagged = new int[100][];
 for (int row = 0; row < 100; row++)
     arrayJagged[row] = new int[100];

Third, you can use a normal array and compute the right index from the row and column:

 int[] array1D = new int[100 * 100];

When you go to access the data, you will do one of the following:

 int row = 3;
 int column = 5; // Pick some numbers...

 Console.WriteLine(array2D[row, column]);
 Console.WriteLine(array1D[row * 100 + column]);

The plain old 2D array is way clearer to understand.

But the question is, which is faster. It is a well-established fact that 2D arrays are slower than their 1D counterparts. But let’s see how much:

|       Method |       Mean |     Error |    StdDev |
|------------- |-----------:|----------:|----------:|
|     1D Array |   7.193 us | 0.0400 us | 0.0374 us |
| Jagged Array |   6.669 us | 0.0410 us | 0.0383 us |
|     2D Array |  10.231 us | 0.0583 us | 0.0546 us |

The 2D array takes about 42% longer. We’re still talking sub-nanosecond for each access, but if you’re doing a ton of it, it can add up. (Even 10,000 accesses here still took only 10 microseconds.)

Notably jagged arrays are faster than 1D arrays. Jagged arrays do different work, because they don’t do a multiplication and an addition, but instead have to hunt down a second object on the heap, but it seems clear that, this time, that work is faster than the arithmetic.

Unfortunately, jagged arrays have the ugliest setup, by far.

I will say that I tend to optimize for readability and maintainability instead of raw speed unless there’s measurable performance problem. That puts me in the camp of preferring 2D arrays over the others. 2D arrays are still quite fast, and the situations where saving a few nanoseconds or even microseconds will matter is quite rare.

But it is an interesting performance comparison anyway.

As a side note, simply indexing into a 1D array was faster (5.888 us) than the other options above. The 1D array only drops behind the jagged array when you need to do that multiplication and addition.