.NET Memory Allocation – Why Do .NET Books Discuss Stack vs Heap Memory Allocation?

net

It seems like every .net book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored – the heap or the stack. Usually it's in the first few chapters and presented as some all-important fact. I think it's even covered on certification exams. Why does stack vs heap even matter to (beginner) .Net developers? You allocate stuff and it just works, right?

Best Answer

I'm becoming convinced that the primary reason this bit of information is considered important is tradition. In unmanaged environments, the disctinction between stack and heap is important and we have to manually allocate and delete the memory we use. Now, garbage collection takes care of the management, so they ignore that bit. I don't think the message has really gotten through that we don't have to care which type of memory is used either.

As Fede pointed out, Eric Lippert has some very interesting things to say about this: https://docs.microsoft.com/en-us/archive/blogs/ericlippert/the-truth-about-value-types.

In light of that information, you could adjust my first paragraph to basically read: "The reason people include this information and assume it is important is because of incorrect or incomplete information combined with needing this knowledge in the past."

For those who think it is still important for performance reasons: What actions would you take to move something from the heap to the stack if you did measure things and find out that it mattered? More likely, you'd find a completely different way of improving performance for the problem area.

Related Topic