Today while returning from office, I had a very good conversation with one of mine friend Sunny Raheja. We were discussing here and there and suddenly he asked to me
“Hey DJ, is there any difference in performance of single dimensional array if I don’t give 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 answer in this book.
So answer of above question goes like this,
Single Dimensional array with Zero based index is having better performance.
Single Dimensional array with Non Zero based index is having slow access of the array values.
To support above statement let us run below code,
In above code
- We are creating an Integer Array
- Size of Array is 2
- Lower bound is 0
On running Output we would get,
Now let us create an array with lower bound 1
In above code
- We are creating an Integer Array
- Size of Array is 2
- Lower bound is 1
On running Output we would get,
If you see the difference in both output; There is * in type of non -Zero based array. So by looking at type (*) complier knows about non-zero index array.
Since we know there is nothing called (*) in c# and CLR does not support declaration or access of variable with *.
So to access elements of non-zero based, Array’s GetValue() and SetValue() method 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); } } }
Leave a Reply