Stack vs Heap

So in relation to my last post on the LCD coding challenge.  A few more examples came up for solving this kata.  As we were discussing memory and speed etc I casually stated

Well if you convert all you classes to structs then that should make things faster.

I’ve heard this a lot but it occurred to me that I have never really tested the theory.  Also I couldn’t answer the question on everyone’s lips which is how much faster.  Therefore I put a quick spike together to test this and below are the results.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Testing creating 100,000,000 heap objects");
            for (int j = 0; j < 10; j++)
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                for (int i = 0; i < 100000000; i++)
                {
                    var person = new PersonClass();
                }

                stopwatch.Stop();
                Console.WriteLine(string.Format("Elaspsed ms: {0}", stopwatch.ElapsedMilliseconds));
            }

            Console.ReadLine();
        }
    }

    public class PersonClass{}

    public struct PersonStruct{}

And below is the summary of the results.  I create 100 million class heap objects and the same number using structs.  I run this in a loop 10 times.

Testing creating 100,000,000 heap objects
Elaspsed ms: 850
Elaspsed ms: 824
Elaspsed ms: 820
Elaspsed ms: 809
Elaspsed ms: 825
Elaspsed ms: 850
Elaspsed ms: 809
Elaspsed ms: 803
Elaspsed ms: 793
Elaspsed ms: 794
Finished!

Testing creating 100,000,000 struct objects
Elaspsed ms: 255
Elaspsed ms: 248
Elaspsed ms: 246
Elaspsed ms: 251
Elaspsed ms: 244
Elaspsed ms: 245
Elaspsed ms: 245
Elaspsed ms: 248
Elaspsed ms: 244
Elaspsed ms: 246
Finished!

As you can see creating the structs are way quicker as we are no longer allocating memory on the heap and are avoiding putting pressure on the GC.  Based on this non-scientific test we would average over 3 times quicker. 

Moral of the story, if you need to create a lot of simple throw away objects in memory and you want the best performance then consider converting your objects to value types.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: