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.

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.