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.
A single dimensional array with a zero based index has better performance.
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:
In the above code:
- We are creating an integer array
- The size of the array is 2
- The lower bound is 0
On running the output we would get is:
Now let us create an array with a lower bound of 1:
In the above code:
- We are creating an integer array
- The size of the array is 2
- The lower bound is 1
Upon running the output we get is:
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);
}
}
}