TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Jagged Array Examples

These C# examples use jagged arrays, which have performance advantages. A jagged array more efficiently stores uneven data.

Jagged arrays. Data comes in various shapes.

Sometimes the shape is uneven. With jagged arrays, we can store efficiently many rows of varying lengths. Any type of data, reference or value, can be used.

Important: Jagged arrays have different performance characteristics. Indexing jagged arrays is fast. Allocating them is somewhat slow.

Example. Let us start. This code is a short (but complete) program you can run in a console project. It creates a jagged array of int elements. It sets values in the array. The program then prints out the result at the end.

ConsoleInt

Based on:

.NET 4.5

C# program that uses jagged arrays

using System;

class Program
{
    static void Main()
    {
	// 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();
	}
    }
}

Output

"1 2"
"0"
"3 4 5"

This example declares a jagged array. The word jagged doesn't even exist in the C# language. This means that you don't need to use this word in your code. Jagged is just a descriptive variable name I use.

Then: It initializes some values in the jagged array. There are lots of square brackets.

Note: This is very different from a 2D array, which uses commas instead of pure brackets.

Next, we see that indexes in the array are assigned to new int arrays. This is because the earlier statement allocates only the list of empty references to arrays. You have to make your own arrays to put in it.

Also: We see the array initializer syntax here, which is less verbose than some other ways.

Array Initializers

Looping over jagged arrays. You will want to examine each item in the jagged array. We must call Length first on the array of references, and then again on each inner array. The Console calls above are just for the example.

Console.WriteLine

2D arrays. We determine how to choose between jagged arrays and 2D arrays. First ask the question: will every row in my collection have the same number of elements? If so, you can consider 2D arrays, but often you have varying numbers of elements.

2D Array

Performance notes. Second, jagged arrays are faster and have different syntax. They are faster because they use the "newarr", vector IL calls internally. The boost is because they are optimized for starting at 0 indexes.

IL: newarrIL Disassembler

Method that is reflected for MSIL test: C#

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
}

Choosing the syntax. Whichever array type you choose, don't select it because of the syntax. It is important to know that the pairs of brackets indicate "jagged," and the comma in the brackets means "2D".

Tip: You can allocate different arrays for each row in jagged arrays separately. This means your program must use 1D arrays in parts.

Methods. You can use the type of the jagged array in method signatures. They will be passed as references, which is important because it eliminates most copying. Only the reference is copied on each function call.

Also: For local variables only, you can use the var implicit type syntax. This makes programs easier to read.

Var

Benchmark. The .NET Framework has optimizations for this specific case. The 2D array cannot take advantage of them. My opinion is that you should always prefer jagged arrays. They have substantial optimizations in the intermediate language level.

Jagged vs. 2D Array

2D array code benchmarked: C#

// 2D array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
	int c = a1[a, x];
    }
}

Jagged array code benchmarked: C#

// Jagged array of 100 x 100 elements.
for (int a = 0; a < 100; a++)
{
    for (int x = 0; x < 100; x++)
    {
	int c = a2[a][x];
    }
}

Results

2D array looping:     4571 ms
Jagged array looping: 2864 ms [faster]

Summary. We used jagged arrays in a C# program. Jagged arrays are fast and easy to use once you learn the slightly different syntax. Prefer them to 2D arrays when performance is a consideration, and they are not more complex to use.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf