Tip To Improve Program Speed While Looping Through Arrays

This tip can improve the speed of the programs that spend a lot of time looping over arrays.

Probably you know from the experience, that when you try to access an invalid array element (say, index 11 in an array of size 10), you will get an IndexOutOfRangeException. To generate this exception and prohibit the dangerous access of the memory beyond your array storage, the run time performs an array bounds check every time you access an array, which checks that the index you supply is lower than the array size.

For example, take a look the code, given below:

  1. int count = 0;  
  2. int[] myarray = new int[10];  
  3. // omitted: fill myarray with some values  
  4. for (int i = 0; i < 10; i++)  
  5. count += myarray[i];  
Here, we simply loop over all the elements of the array and add them together.

What the compiler actually produces looks something like the result of this code.
  1. for (int i = 0; i < 10; i++)  
  2. {  
  3. if (i >= myarray.Length)  
  4. throw new IndexOutOfRangeException();  
  5. count += myarray[i];  
  6. }  
Now, the hidden cost is only a simple expression for each array access, but if you have many or very large arrays which get looped over often, it can add up.

There are two ways to let the compiler skip the bounds checks and speed up the array code.

The first way is to use Array.Length as the upper bound of the loop variable and use the unmodified loop variable to index the array:
  1. for (int i = 0; i < myarray.Length; i++)  
  2. count += myarray[i];  
The second way is to loop over the array with foreach,
  1. foreach (int x in myarray)  
  2. count += x;  
In both cases, the compiler can be sure that the array index will never be outside its bounds and skip the bounds check.

 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now