Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Array.GetLength(dimension) in C# actually work?

Tags:

arrays

c#

When using Array.GetLength(dimension) in C#, does the size of the array actually get calculated each time it is called, or is the size cached/stored and that value just gets accessed?

What I really want to know is if setting a local variable to the length of the dimension of an array would add any efficiency if used inside a big loop or if I can just call array.GetLength() over and over w/o any speed penalty.

like image 304
devuxer Avatar asked Jul 04 '10 21:07

devuxer


1 Answers

It is most certainly a bad idea to start caching/optimizing by yourself here.

When dealing with arrays, you have to follow a standard path that the (JIT) optimizer can recognize. If you do, not only will the Length property be cached but more important the index bounds-check can be done just once before the loop.

When the optimizer loses your trail you will pay the penalty of a per-access bounds-check.

This is why jagged arrays (int[][]) are faster than multi-dim (int[,]). The optimization for int[,] is simply missing. Up to Fx2 anyway, I didn't check the status of this in Fx4 yet.

If you want to research this further, the caching you propose is usually called 'hoisting' the Length property.

like image 196
Henk Holterman Avatar answered Sep 22 '22 11:09

Henk Holterman