Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences between a multidimensional array and an array of arrays in C#?

What are the differences between multidimensional arrays double[,] and array-of-arrays double[][] in C#?

If there is a difference, what is the best use for each one?

like image 565
ecleel Avatar asked Feb 28 '09 07:02

ecleel


People also ask

Is two-dimensional array and multidimensional array same?

Two – dimensional array is the simplest form of a multidimensional array.

Is array of array a multidimensional?

A multidimensional array is an array containing one or more arrays.


1 Answers

Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.

If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.

Consider the following methods:

static void SetElementAt(int[][] array, int i, int j, int value) {     array[i][j] = value; }  static void SetElementAt(int[,] array, int i, int j, int value) {     array[i, j] = value; } 

Their IL will be the following:

.method private hidebysig static void  SetElementAt(int32[][] 'array',                                                     int32 i,                                                     int32 j,                                                     int32 'value') cil managed {   // Code size       7 (0x7)   .maxstack  8   IL_0000:  ldarg.0   IL_0001:  ldarg.1   IL_0002:  ldelem.ref   IL_0003:  ldarg.2   IL_0004:  ldarg.3   IL_0005:  stelem.i4   IL_0006:  ret } // end of method Program::SetElementAt  .method private hidebysig static void  SetElementAt(int32[0...,0...] 'array',                                                     int32 i,                                                     int32 j,                                                     int32 'value') cil managed {   // Code size       10 (0xa)   .maxstack  8   IL_0000:  ldarg.0   IL_0001:  ldarg.1   IL_0002:  ldarg.2   IL_0003:  ldarg.3   IL_0004:  call       instance void int32[0...,0...]::Set(int32,                                                            int32,                                                            int32)   IL_0009:  ret } // end of method Program::SetElementAt 

When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.

like image 77
okutane Avatar answered Sep 24 '22 11:09

okutane