1

I was working my way through simple tasks on arrays and had this task:

Displays all the elements of an array.

My solution to this problem was to create a variable n that will store Array.Length value. Then I would use it in for-statement. The suggested solution was even more straight forward - it would just use inside the for-statement Array.Length property.

My solution:

int[] array = { 0, 1, 3, 4, 5, 2, 1, -4, -1, 10, 55 };
int n = array.Length;
for (int i = 0; i < n; i++)
{
Console.WriteLine(array[i]);
}

Suggested solution:

int[] array = { 0, 1, 3, 4, 5, 2, 1, -4, -1, 10, 55 };
for(int i = 0; i < array.Length; i++)
{
Console.WriteLine(array[i]);
}

My concern is that if we put Array.Length Property inside a loop statement means that it will re-calculate it n-times (where n = Array.Length). Shouldn't it be bad considering that n can be a very big number?

Is there any difference in terms of processing speed or used storage? Or are they just equal options?

  • 2
    "*Shouldn't it be bad considering that n can be a very big number?*" -- the length of an array is stored in a header at the start of the array -- it's very cheap to fetch it – canton7 Apr 07 '21 at 13:29
  • 1
    The length of the array is stored as part of the array. It isn't recalculated every time. –  Apr 07 '21 at 13:30
  • 2
    In fact, in your case, the JIT knows that your array is 11 elements long, and hard-codes the loop as `for (int i = 0; i < 11; i++)`! If it can't work this out, it fetches the array length once and stores it in a register. [Link](https://sharplab.io/#v2:EYLgxg9gTgpgtADwGwBYA0AXEBDAzgWwB8ABAJgEYBYAKGIGYACMhgYQYG8aHunHiUGAWQAUASwB2GANoBdBtihRsATwCUHLjy0AzaAzGSGohgF4GABgDcRhgB55ilQDoAMjHEBzDAAtrogNT+qppa3JzUoZFM5ACcwgpKylKiMqqWIaEAvhnZETwZ9EwCIurhUUaSsg6JphwWaAzkDXQN6AwArA2kDU0McG1wveTmDe3tDJnpeZG6UPoSGDZmVjb2Cc5unj5+gcHToWXlPMSx8Y5JKWkZWrk3NJlAA=) – canton7 Apr 07 '21 at 13:31
  • 3
    Apart from the fact that arrays are optimized since they can't be resized, it should not matter much with other collections that have a `Count` property(like `List`). They should be implemented in a way that they dont need to "calculate" anything but just return a variable value. Note that you might even create a bug if you store the value before the loop, if the collection is modifed while you are enumerating it you don't get the current value but use an old. – Tim Schmelter Apr 07 '21 at 13:36
  • You can also just use foreach, it'll get optmized into the same thing. https://stackoverflow.com/questions/64112501/in-net-core-is-for-and-foreach-now-the-same-when-iterating-over-an-array-of-val – MikeJ Apr 07 '21 at 13:48
  • In addition to my last comment: don't confuse the `Count`-property with the `Count`-method(LINQ's [`Enumerable.Count`](https://referencesource.microsoft.com/#System.Core/System/Linq/Enumerable.cs,41ef9e39e54d0d0b)). If the sequence is not a collection but a query it will enumerate it fully every time. So here you should be careful. – Tim Schmelter Apr 07 '21 at 14:28

1 Answers1

-2

The comparison-statement will be executed every time. Like other people already mentioned: It doesn't matter for Array.Length since this attribute is internally stored in the array, but you should avoid evaluating the size every time like this:

// if the result of getSize-function never 
// changes, do not call it in the statement
for (var i = 0; i < getSize(); i++) {

}
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
  • @TimSchmelter I mentioned a for-behavior that frequently leads to bugs or bad application performance, directly linked to OPs question. I am sure that a lot of beginner-level programmers will be thankful for my advice. I have clarified my statement. – ˈvɔlə Apr 07 '21 at 14:09