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:
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); } }}
Single Dimensional Array Performance
Optional and Named Arguments in C#
So what is the answer? How much of a performance degradation is there for a non-zero based lower bound? How much of a difference is there in the generated machine code? I assume that the difference in machine code would be one machine instruction. How much of a performance degradation is there for people to adjust an index's lower bound to be zero based when it would be easier to use a different lower bound?