Wednesday, June 12, 2013

Performances difference between Structure and Class.

Hi friend, Hope you guise are very fine. In today’s pose I will talk about performance between structure and class.

So guys, by accepting that you are pretty much well know about structure and class in C# or at least in your favorite programming language If they are present there. Ok, if you thinking that “long back ago I had learned structure and in daily coding life never used”, then you are among those 95 % Developer. Don’t worry ,me too with you J.
And what about class ? Yes now and then we implement class in our daily routine project development.

Now my question is “ Which one is faster , class or structure”? I expect that you are thinking that “Never test it”. Ok Then let’s test it here. Have a look of below code.
Here is my class and Structure 

   
  struct MyStructure
    {
        public string Name;
        public string Surname;
    };

    class MyClass
    {
        public string Name;
        public string Surname;
    }
       static void Main(string[] args)
        {
            MyStructure [] objStruct = new MyStructure[1000];
            MyClass[] objClass = new MyClass[1000];


            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                objStruct[i] = new MyStructure();
                objStruct[i].Name = "Sourav";
                objStruct[i].Surname = "Kayal";
            }
            sw.Stop();
            Console.WriteLine("For Structure:- "+ sw.ElapsedTicks);
            sw.Restart();

            for (int i = 0; i < 1000; i++)
            {
                objClass[i] = new MyClass();
                objClass[i].Name = "Sourav";
                objClass[i].Surname = "Kayal";
            }
            sw.Stop();
            Console.WriteLine("For Class:- " + sw.ElapsedTicks);


            Console.ReadLine();
        }
And here is the result.




Now it’s clear that structure is much more faster than Class. Yes, I have test this code in release mode and taken at least 20 output to bring program in stable position.
Now big question is “why structure is faster than class” ?
As we know structure variable are value type and in one location the value (or structure variable) get store.
And class object are reference type . In case of object type the reference get create and the value get store in some other location of memory . Basically the value store in manageable heap and pointer get create in stack. And to implement a object In memory like this fashion ,generally it will take more time than structure variable.




No comments:

Post a Comment