Wednesday, April 23, 2014

What's the difference between the heap and stack in C# .NET?

This question has popped up several times while I have been studying data structures for an upcoming interview. The best answer I've found so far is this blog post by Eric Lippert at Microsoft. A short summary:

  • There are three kinds of storage locations: stack locations, heap locations, and registers.
  • Long-lived storage locations are always heap locations.
  • Short-lived storage locations are always stack locations or registers.
  • There are some situations in which it is difficult for the compiler or runtime to determine whether a particular storage location is short-lived or long-lived. In those cases, the prudent decision is to treat them as long-lived. In particular, the storage locations of instances of reference types are always treated as though they are long-lived, even if they are provably short-lived. Therefore they always go on the heap.

Always keep in mind that "The type system has nothing whatsoever to do with the storage allocation strategy." (my own paraphrase)