Single Dimensional Array Performance



Today while returning from the office, I had a very good conversation with one of my friends Sunny Raheja. We were discussing how a Cloud or to be particular Windows Azure could be useful to enhance lives of farmers in our country and suddenly he asked me:

"Hey DJ, is there any difference in performance of single dimensional array if I don't give a lower bound as 0 or if lower bound is non-zero"

I thought for a while and replied to him tune in for my next blog post.

I was not very sure about the answer at that point of time so as soon as I reached home, I took CLR via C# because I was sure; I would get an answer in that book.

So the answer of the above question goes like this.

Array1.gif

A single dimensional array with a zero based index has better performance.

Array2.gif

A single dimensional array with a non-zero based index has slower access of the array values.

To support the above statement let us run the following code:

Array3.gif

In the above code:

  1. We are creating an integer array
  2. The size of the array is 2
  3. The lower bound is 0

On running the output we would get is:

Array4.gif

Now let us create an array with a lower bound of 1:

Array5.gif

In the above code:
  1. We are creating an integer array
  2. The size of the array is 2
  3. The lower bound is 1

Upon running the output we get is:

Array6.gif

If you see the difference in both outputs; there is * in the type of the non-zero based array. So by looking at type (*) the complier knows about a non-zero index array.
 
Since we know there is nothing called (*) in C# and CLR does not support a declaration or access of a variable with *.

So to access elements of a non-zero based, Array's GetValue() and SetValue() methods can be used and it would reduce the performance.

I hope Sunny would be satisfied by this answer..

Program.cs

using System;

namespace ConsoleApplication21
{
    class Program
    {
        static void Main(string[] args)
        {

            Array myArray;
            myArray = new string[0];
            Console.WriteLine(myArray.GetType());
            Console.ReadKey(true);

            myArray = Array.CreateInstance(typeof(string),
                      new Int32[] { 2 },
                      new Int32[] { 0 });
            Console.WriteLine(myArray.GetType());
            Console.ReadKey(true);

            myArray = Array.CreateInstance(typeof(string), 
                       new Int32[] { 2 },
                       new Int32[] { 1 });
            Console.WriteLine(myArray.GetType());


            Console.ReadKey(true);
        }
    }
}

Up Next
    Ebook Download
    View all
    Learn
    View all