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?
cjagged-arraysmultidimensional-array
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?
Best Answer
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:
Their IL will be the following:
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.