Efficiently manage a variable number of values in a jagged array. We have several rows of data, such as ints, and want to store them together in a single data structure. Jagged arrays are ideal for this. We must learn the syntax and then investigate the reasons why their performance is good. Our solution must be effective and efficient.
How can we use jagged arrays? First I show some syntax of how you can add elements ('rows') to a jagged array after declaring it. What the first example does is create three rows in a jagged array in different ways. Then it loops through the jagged array and prints out each int value.
/// <summary>
/// Example class.
/// </summary>
class JaggedArray
{
/// <summary>
/// Example method.
/// </summary>
public JaggedArray()
{
// Declare local jagged array with 3 rows.
int[][] jagged = new int[3][];
// Create a new array in the jagged array, and assign it.
jagged[0] = new int[2];
jagged[0][0] = 1;
jagged[0][1] = 2;
// Set second row, initialized to zero.
jagged[1] = new int[1];
// Set third row, using array initializer.
jagged[2] = new int[3] { 3, 4, 5 };
// Print out all elements in the jagged array.
for (int i = 0; i < jagged.Length; i++)
{
int[] innerArray = jagged[i];
for (int a = 0; a < innerArray.Length; a++)
{
Console.Write(innerArray[a] + " ");
}
Console.WriteLine();
}
}
}
What's the difference? Jagged arrays are faster and have different syntax. They are faster because they use the "newarr" (vector) IL calls internally. I don't know all the details, but the boost is because they are optimized for starting at 0 indexes. The next example shows some code I compared in IL DASM.
/// <summary>
/// Shows jagged array vs. 2D array.
/// </summary>
private static void CompareIL()
{
int[,] twoD = new int[1, 1]; // 1 x 1 array
twoD[0, 0] = 1;
int[][] jag = new int[1][];
jag[0] = new int[1];
jag[0][0] = 1; // 1 x 1 jagged array
}
Quite a lot faster. This is apparently because the .NET runtime has many optimizations for this specific case, and for some reason the 2D array cannot take advantage of them. My opinion is that you should always use jagged arrays when possible. I don't know the difference in memory usage. This data is based on 10 million repetitions.
| Version |
Time in ms 10 million tests |
Details |
| 2D array | 422 | I tested the fastest method for using 2D arrays (using Length). |
| Jagged array | 109 | - |
Jagged arrays are fast and easy to use once you master the slightly different syntax. Prefer them to 2D arrays when performance is a consideration, and they are not more complex more to use. Investigating IL can be useful for understanding .NET internals. Finally, put bright rainbow colors on your bar charts.