Monday, June 10, 2013

Boxing and Unboxing in C#

Hi Guys how are you ? I am fine. Just now I was thing to write something in blog but not getting topic to write. And at last have chosen one to talk.
Let’s learn boxing and unboxing in C# today.  Rather to talk general boxing and unboxing I will show you how boxing and unboxing impact on our code. (Now a days I am serious about performance of my code, But in early days I was not much J)
Let’s start with general concept.

Boxing:- When we try to convert value type to reference type or object type then boxing take place.
Example:-

     static void Main(string[] args)
        {
            int a = 100;
            Object myobj = (Object)a;
            Console.Write(myobj);
            Console.ReadLine();
        }



Here a is integer variable and I am converting it into object type. I am explicitly
converting to Object type. It’s called Boxing.

And I can expect that you already guess that what is unboxing? Yes, just to sake of completeness I will discuss Unboxing.

Unboxing:- Unboxing is nothing but to convert object type to value type.
Very simple just have a look at below code.

static void Main(string[] args)
        {
            Object myobj = 100;
            int Value = (int)myobj;
            Console.Write(Value);
            Console.ReadLine();
        }




Now let’s see for boxing and unboxing how much extra time is taken by .NET Runtime.
Let’s look below example.
static void Main(string[] args)
        {
            List<Int32> li = new List<int>();
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int i = 0; i < 10000; i++)
            {
                li.Add(i);
            }
            sw.Stop();

            Console.Write("Using Arraylist(Object)"+ sw.ElapsedTicks + "\n");
            sw.Reset();

            sw.Start();
            Int32[] a = new Int32[10000];
            for (int i = 0; i < 10000; i++)
            {
                a[i] = i;
            }
            sw.Stop();
            Console.Write("Using Value(Integer Array)"+ sw.ElapsedTicks);
            Console.ReadLine();
        }


Here I am doing same operation using arrayList which is reference type and using integer array , Which is value type. And it’s clearly seen that Array list is taking much more time to do the same operation.
Now, question is why ? Yes, what you guess is right. It’s  taking time to convert value type to reference type.
I have given this example to show you ,if you did ‘n choose perfect data type then how much our application might slow down.

So be smart and choose perfect data type. 

1 comment: