Generics vs Object performance
<p>I'm doing practice problems from MCTS Exam 70-536 Microsft .Net Framework Application Dev Foundation, and one of the problems is to create two classes, one generic, one object type that both perform the same thing; in which a loop uses the class and iterated over thousand times. And using the timer, time the performance of both. There was another post at <a href="http://stackoverflow.com/questions/221467/c-generics-question">C# generics question</a> that seeks the same questoion but nonone replied.</p>

<p>Basically if in my code I run the generic class first it takes loger to process. If I run the object class first than the object class takes longer to process. The whole idea was to prove that generics perform faster.</p>

<p>I used the original users code to save me some time. I didn't particularly see anything wrong with the code and was puzzled by the outcome. Can some one explain why the unusual results?</p>

<p>Thanks,</p>

<p>Risho</p>

<p>Here is the code:</p>

<pre><code>class Program
{
    class Object_Sample
    {            
        public Object_Sample()
        {
            Console.WriteLine("Object_Sample Class");
        }

        public long getTicks()
        {
            return DateTime.Now.Ticks;
        }

        public void display(Object a)
        {
            Console.WriteLine("{0}", a);
        }
    }

    class Generics_Samle&lt;T&gt;
    {            
        public Generics_Samle()
        {
            Console.WriteLine("Generics_Sample Class");
        }

        public long getTicks()
        {
            return DateTime.Now.Ticks;
        }

        public void display(T a)
        {
            Console.WriteLine("{0}", a);
        }
    }

    static void Main(string[] args)
    {            
        long ticks_initial, ticks_final, diff_generics, diff_object;
        Object_Sample OS = new Object_Sample();
        Generics_Samle&lt;int&gt; GS = new Generics_Samle&lt;int&gt;();

        //Generic Sample
        ticks_initial = 0;
        ticks_final = 0;
        ticks_initial = GS.getTicks();

        for (int i = 0; i &lt; 50000; i++)
        {
            GS.display(i);
        }
        ticks_final = GS.getTicks();
        diff_generics = ticks_final - ticks_initial;

        //Object Sample
        ticks_initial = 0;
        ticks_final = 0;
        ticks_initial = OS.getTicks();

        for (int j = 0; j &lt; 50000; j++)
        {
            OS.display(j);
        }

        ticks_final = OS.getTicks();
        diff_object = ticks_final - ticks_initial;

        Console.WriteLine("\nPerformance of Generics {0}", diff_generics);
        Console.WriteLine("Performance of Object {0}", diff_object);

        Console.ReadKey();
    }
}
</code></pre>
