-3

I know that a jagged array is an array of arrays where the length of the inner arrays can be of any length.

With a multi-dimensional array, the inner arrays all have to be of the same length.

But if I have an array of arrays (jagged) where all of the inner arrays are of the same length, then what's the difference between this and multi-dimensional array?

the man
  • 1,131
  • 1
  • 8
  • 19

1 Answers1

2

Use of these two types of arrays, once allocated, wouldn't be very different. But there are a lot of differences in implementation and allocation.

Allocation It is simpler to allocate a multidimensional array. Simply: new int[4, 2, 3]; For a jagged array, you'd need a lot more steps and a loop

Implementation A multidimensional is essentially stored in a single block of memory (or memory address space). With a jagged array, every sub-array is potentially in a different part of memory. This can have impact on caching and performance but the bigger hit is you get N indirections to access a single item, or a lookup for each dimension. For a multidimensional array, given the N indexes, the memory location can be determined arithmetically by the N indices. For a jagged array, you need a memory read for each index taking you to a new block of memory. A jagged array also has a lot more overhead storing the dimensions of each subarray, although it is pretty insignificant.

Usage for usage, really, the difference is more edge case checking. You can check the dimensions of a multidimensional array prior to accessing it whether the indices are within bounds. For a jagged array, to avoid throwing exceptions, you'd need to access each dimension one at a time to check the boundaries.

In other words, use a multidimensional array in this case. If you need a jagged array or it makes sense for you data model, then use it, but it is more complicated.

Garr Godfrey
  • 8,257
  • 2
  • 25
  • 23