Myth: Value Types are always stored on stack

We are always taught and learnt to be that the value types are always stored on the Stack, and this is not true to its entirety. There is this one question which always, from the time I started working on C#, bothered me to ask myself, but until recent time I have never attempted to research to find the reason for it, how shameless of me.

Question:  If the value types are used as part of the object instance, where would that be stored, still on the stack?

So the answer to this particular question at least arises one point which contradicts this famous myth. The answer is – Value types are stored on the heap as part of the object instance, not on the stack.

In process of finding the reason, I came across this topic from Eric  Lippert, http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

He says: In the Microsoft implementation of C# on the desktop CLR, value types are stored on the stack when the value is a local variable or temporary that is not a closed-over local variable of a lambda or anonymous method, and the method body is not an iterator block, and the jitter chooses to not enregister the value.”

Few of other points from his blog:

  1. There are three types of values: Instances of Value types, Instances of Reference Types and, References
  2. There are three kinds of storage locations: Stack, heap and registers
  3. Every storage location has a “life time”. That is, a period of time in which storage location’s contents is valid.
  4. The time between a start of execution of a particular method and the method returning normally or throwing an exception is the “activation period” for that method execution.
  5. If the life time of the value is greater than the activation period, then it’s called long lived value, otherwise it is short lived.
  6. So the choice of the storage location for the complier mostly depends life time of the storage location. How? If the required life time of the storage location is greater than the activation period of the current method execution than the storage is said to be “long lived”, otherwise it is “short lived”
  7. Long lived storage location are always heap locations.
  8. Short lived storage location are always stack or registers.
  9. References and value types are same as far as their storage is concerned: they either on stack or registers or heap, depending whether the storage of the value needs to be short lived or long lived.
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