Member-only story

What Is Faster In C#: An int[] or an int[,]?

Mark Farragher
4 min readMar 15, 2019

In this article I’ll take a look at the different types of arrays in C#. Understanding the differences between array types will help you pick the correct data structure for every occasion.

Check out the following code:

The MeasureTestA method sets up a 3-dimensional array, loops through each array element, and sets it to the value ‘3’.

The MeasureTestB method does pretty much the same, but it uses a 1-dimensional array instead and calculates the array offset by hand using the i, j, and k loop variables.

That shouldn’t make any difference, right? You would expect that 3-dimensional arrays in .NET use the same logic as what I’ve explicitly coded in MeasureTestB.

Well, let’s take a look:

Did you see that coming?

The 3-dimensional array code in MeasureTestA is 31% slower than the 1-dimensional array code in MeasureTestB!

What’s going on here?

Let’s find out. We’ll start by looking at the 3-dimensional array code in MeasureTestA. The inner loop compiles to very efficient intermediate language:

The highlighted section is where the magic happens. The Array.Set method uses the i, j, and k indices to write the value ‘3’ directly into memory.

That’s just 6 instructions with one method call. Not bad at all!

Now let’s take a look at the inner loop of MeasureTestB:

Responses (1)

Write a response