csharp / intermediate
Snippet
Optimizing Matrix Representation with Jagged Arrays
Unlike multidimensional arrays (e.g., int[,]), jagged arrays are 'arrays of arrays'. They are more memory-efficient when rows have unequal lengths (sparse data) and often perform better because the CLI can optimize the bounds-checking for single-dimensional arrays more effectively.
snippet.cs
csharp
1
2
3
4
5
6
7
8
9
int[][] jaggedMatrix = new int[3][];jaggedMatrix[0] = [1, 2];jaggedMatrix[1] = [3, 4, 5, 6];jaggedMatrix[2] = [7];foreach (var row in jaggedMatrix){Console.WriteLine($"Row length: {row.Length}");}
Breakdown
1
int[][] jaggedMatrix = new int[3][];
Initializes an array that will hold three other arrays (the rows).
2
jaggedMatrix[1] = [3, 4, 5, 6];
Each row can be initialized with a unique length, saving space compared to a fixed-size grid.