Why are multi-dimensional arrays in .NET slower than normal arrays?
Single dimensional arrays with a lower bound of 0 are a different type to either multi-dimensional or non-0 lower bound arrays within IL (vector
vs array
IIRC). vector
is simpler to work with - to get to element x, you just do pointer + size * x
. For an array
, you have to do pointer + size * (x-lower bound)
for a single dimensional array, and yet more arithmetic for each dimension you add.
Basically the CLR is optimised for the vastly more common case.
Array bounds checking?
The single-dimension array has a length member that you access directly - when compiled this is just a memory read.
The multidimensional array requires a GetLength(int dimension) method call that processes the argument to get the relevant length for that dimension. That doesn't compile down to a memory read, so you get a method call, etc.
In addition that GetLength(int dimension) will do a bounds check on the parameter.