## Performance of Non-Zero lower bound Single Dimensional Array

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

1. We are creating an Integer Array
2. Size of Array is 2
3. Lower bound is 0

On running Output we would get,

Now let us create an array with lower bound 1

In above code

1. We are creating an Integer Array
2. Size of Array is 2
3. 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());

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

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

}
}
}

```

### 6 responses to “Performance of Non-Zero lower bound Single Dimensional Array”

1. Hey… thanks man..
good explanation 🙂

2. […] back while browsing over internet when I found an article written one of my buddy Dhananjay Kumar here, I thought how could I forget this important section of C# language, hence in this post, I will […]

3. Nice.

Tks.

4. Nice sir. Well Explained

5. Anonymous

Very userful tips, keep it up.

6. […] Performance of Non-Zero lower bound Single Dimensional Array […]