Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Articles » C# Heap(ing) Vs Stack(ing) in .NET: Part I

C# Heap(ing) Vs Stack(ing) in .NET: Part I

Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications.

Author Rank :
Page Views : 326864
Downloads : 1828
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
StackVsHeap_Part1.zip
 
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


Even though with the .NET framework we don't have to actively worry about memory management and garbage collection (GC), we still have to keep memory management and GC in mind in order to optimize the performance of our applications. Also, having a basic understanding of how memory management works will help explain the behavior of the variables we work with in every program we write.  In this article I'll cover the basics of the Stack and Heap, types of variables and why some variables work as they do.

There are two places the .NET framework stores items in memory as your code executes.  If you haven't already met, let me introduce you to the Stack and the Heap.  Both the stack and heap help us run our code.  They reside in the operating memory on our machine and contain the pieces of information we need to make it all happen.

Stack vs. Heap: What's the difference?

The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called").  The Heap is more or less responsible for keeping track of our objects (our data, well... most of it - we'll get to that later.).

Think of the Stack as a series of boxes stacked one on top of the next.  We keep track of what's going on in our application by stacking another box on top every time we call a method (called a Frame).  We can only use what's in the top box on the stack.  When we're done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to hold information (not keep track of execution most of the time) so anything in our Heap can be accessed at  any time.  With the Heap, there are no constraints as to what can be accessed like in the stack.  The Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet - we can grab what we need quickly.  The Stack is like the stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.

heapvsstack1.gif

The picture above, while not really a true representation of what's happening in memory, helps us distinguish a Stack from a Heap.
 
The Stack is self-maintaining, meaning that it basically takes care of its own memory management.  When the top box is no longer used, it's thrown out.  The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean (no one wants dirty laundry laying around... it stinks!).

What goes on the Stack and Heap?

We have four main types of things we'll be putting in the Stack and Heap as our code is executing: Value Types, Reference Types, Pointers, and Instructions. 

Value Types:

In C#, all the "things" declared with the following list of type declarations are Value types (because they are from System.ValueType):

  • bool
  • byte
  • char
  • decimal
  • double
  • enum
  • float
  • int
  • long
  • sbyte
  • short
  • struct
  • uint
  • ulong
  • ushort

Reference Types:

All the "things" declared with the types in this list are Reference types (and inherit from System.Object... except, of course, for object which is the System.Object object):

  • class
  • interface
  • delegate
  • object
  • string

Pointers:

The third type of "thing" to be put in our memory management scheme is a Reference to a Type. A Reference is often referred to as a Pointer.  We don't explicitly use Pointers, they are managed by the Common Language Runtime (CLR). A Pointer (or Reference) is different than a Reference Type in that when we say something is a Reference Type is means we access it through a Pointer.  A Pointer is a chunk of space in memory that points to another space in memory.  A Pointer takes up space just like any other thing that we're putting in the Stack and Heap and its value is either a memory address or null. 

heapvsstack2.gif

Instructions:

You'll see how the  "Instructions" work later in this article...

How is it decided what goes where? (Huh?)

Ok, one last thing and we'll get to the fun stuff.

Here are our two golden rules:

  1. A Reference Type always goes on the Heap - easy enough, right? 

  2. Value Types and Pointers always go where they were declared.  This is a little more complex and needs a bit more understanding of how the Stack works to figure out where "things" are declared.

The Stack, as we mentioned earlier, is responsible for keeping track of where each thread is during the execution of our code (or what's been called).  You can think of it as a thread "state" and each thread has its own stack.  When our code makes a call to execute a method the thread starts executing the instructions that have been JIT compiled and live on the method table, it also puts  the method's parameters on the thread stack.  Then, as we go through the code and run into variables within the method they are placed on top of the stack.  This will be easiest to understand by example...

Take the following method.

           public int AddFive(int pValue)
          {
                int result;
                result = pValue + 5;
               
return result;
          }

Here's what happens at the very top of the stack.  Keep in mind that what we are looking at is placed on top of many other items already living in the stack:

Once we start executin ghte method, the method's parameters are placed on the stack (we'll talk more about passing parameters later).

NOTE : the method does not live on the stack and is illustrated just for reference.

heapvsstack3.gif

Next, control (the thread executing the method) is passed to the instructions to the AddFive() method which lives in our type's method table, a JIT compilation is performed if this is the first time we are hitting the method.

heapvsstack4.gif

As the method executes, we need some memory for the "result" variable and it is allocated on the stack.

 heapvsstack5.gif

The method finishes execution and our result is returned.

heapvsstack6.gif

And all memory allocated on the stack is cleaned up by moving a pointer to the available memory address where AddFive() started and we go down to the previous method on the stack (not seen here).

heapvsstack7.gif

In this example, our "result" variable is placed on the stack.  As a matter of fact, every time a Value Type is declared within the body of a method, it will be placed on the stack.

Now, Value Types are also sometimes placed on the Heap.  Remember the rule, Value Types always go where they were declared?  Well, if a Value Type is declared outside of a method, but inside a Reference Type it will be placed within the Reference Type on the Heap.

Here's another example.

If we have the following MyInt class (which is a Reference Type because it is a class):

          public class MyInt
          {         
            
public int MyValue;
          }

and the following method is executing:

          public MyInt AddFive(int pValue)
          {
                MyInt result = new MyInt();
                result.MyValue = pValue + 5;
                return result;
          }

Just as before, the thread starts executing the method and its parameters are placed on sthe thread's stack.

heapvsstack8.gif

Now is when it gets interesting...

Because MyInt is a Reference Type, it is placed on the Heap and referenced by a Pointer on the Stack.

heapvsstack9.gif

After AddFive() is finished executing (like in the first example), and we are cleaning up...

heapvsstack10.gif

we're left with an orphaned MyInt in the heap (there is no longer anyone in the Stack standing around pointing to MyInt)!

heapvsstack11.gif

This is where the Garbage Collection (GC) comes into play.  Once our program reaches a certain memory threshold and we need more Heap space, our GC will kick off.  The GC will stop all running threads (a FULL STOP), find all objects in the Heap that are not being accessed by the main program and delete them.  The GC will then reorganize all the objects left in the Heap to make space and adjust all the Pointers to these objects in both the Stack and the Heap.  As you can imagine, this can be quite expensive in terms of performance, so now you can see why it can be important to pay attention to what's in the Stack and Heap when trying to write high-performance code.

Ok... That great, but how does it really affect me?

Good question. 

When we are using Reference Types, we're dealing with Pointers to the type, not the thing itself.  When we're using Value Types, we're using the thing itself.  Clear as mud, right?

Again, this is best described by example.

If we execute the following method:

          public int ReturnValue()
          {
                int x = new int();
                x = 3;
                int y = new int();
                y = x;      
                y = 4;         
               
return x;
    
      }

We'll get the value 3.  Simple enough, right?

However, if we are using the MyInt class from before

     public class MyInt
          {

                public int MyValue;
          }

and we are executing the following method:

          public int ReturnValue2()
          {
                MyInt x = new MyInt();
                x.MyValue = 3;
                MyInt y = new MyInt();
                y = x;                 
                y.MyValue = 4;              
                
return x.MyValue;
          }

What do we get?...    4!

Why?...  How does x.MyValue get to be 4?... Take a look at what we're doing and see if it makes sense:

In the first example everything goes as planned:

          public int ReturnValue()
          {
                int x = 3;
                int y = x;    
                y = 4;
               
return x;
          }

heapvsstack12.gif

In the next example, we don't get "3" because both variables "x" and "y" point to the same object in the Heap.

          public int ReturnValue2()
          {
                MyInt x;
                x.MyValue = 3;
                MyInt y;
                y = x;                
                y.MyValue = 4;
                
return x.MyValue;
          }

heapvsstack13.gif

Hopefully this gives you a better understanding of a basic difference between Value Type and Reference Type variables in C# and a basic understanding of what a Pointer is and when it is used.  In the next part of this series, we'll get further into memory management and specifically talk about method parameters.

For now...

Happy coding.

Part I | Part II | Part III | Part IV

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Illustrative example by B On February 8, 2006
I made a snippet of code that illustrates how a stuct handles delegates differently than a class. Run the code, then change the declaration 'public struct testStruct' to a class and you get the opposite result. Apparently, in a struct, test is stored by value instead of by reference, thus changes are lost. Any comment appreciated since I am still trying to make sense of this article:
 

using System;
namespace HeapVsStack
{
 class HeapVsStack
 {
  delegate void aDelegate();
  struct testBlock //DIFFERENT RESULT with: class testBlock
  {
   bool test;
   public testBlock(int x)
   {
    test = true;
    MakeTestFalseWithDelegate(new aDelegate(MakeTestFalse));
    System.Console.ReadLine();
   }
   void MakeTestFalse()
   {
    Console.WriteLine("Making test false");
    test = false;
   }
   void MakeTestFalseWithDelegate(aDelegate adelegate)
   {
    adelegate();
    Console.WriteLine("delegate result: " + test);
   }
  }

  static void Main(string[] args)
  {
   testBlock t = new testBlock(0);
  }
 }
}

Reply | Email | Modify 
Illustrative example by Matthew On February 12, 2006

This is a great question.  It does get into territory a little deeper than I intended to go with this introductory article.  To give a proper explaination of what is happening, I just wrote an article on boxing that deals with the situation you are running into that will go into more detail if you are interested.

In brief, what's happening in your code sample is that the struct is being boxed when the delegate is created.  When we execute the method via. the delegate we are really updating a copy of the object that was boxed to the Heap (we are no longer dealing with the object on the Stack). 

In the case when we use a class instead of the struct, the object lives on the Heap the whole time and we aren't dealing with two objects any more, so we get results more along the lines of what would be expected.

Reply | Email | Modify 
.Net doubts by srikanth On October 10, 2006

What is the difference between Response.Redirect and server.Transfer Give me a detailed explanation.and give me the explanation about request.forms and request.QueryString

Reply | Email | Modify 
Re: .Net doubts by Veenu On June 7, 2010
Response.Redirect kills the object of current page and moves to next page to which you have redirected, and url of browser also gets change, we also need then state management while using Response.Redirect to access the value of previous page  now. But when we use Server.Transfer, object of current page remains alive and we move on next page,suppose if you have used 20 pages and used server.transfer then 20 objects will remain alive in memory.
So if you are using heavy pages then server.transfer is not a good option, but if your application needs values from previous pages object without using state management then go  for server.transfer, else its always better to use Response.redirect....

Please let me know if i am wrong somewhere...
Reply | Email | Modify 
Repeater by srikanth On October 10, 2006
What is the DataRepeater,DataList,DataGrid what is the Main Difference between Both of us. Give me the brief explanation. if i use paging and adding controls to the dataRepeater
Reply | Email | Modify 
stack question by dak On January 4, 2007

In the example you have illustrated how does the control go to the AddFive method without popping out the pValue parameter(since pValue is @ the top of the stack)

Reply | Email | Modify 
Is 'System.Object obj' an exceptional case? by Anugrah On January 8, 2008
As you have said above that "all reference types are stored on heap except Sytem.Object myObject". Can you provide more details that why instance of class System.Object is not stored on Heap?
Reply | Email | Modify 
Re: Is 'System.Object obj' an exceptional case? by Matthew On January 22, 2008
I guess I wasn't that clear when I said

>> "All the "things" declared with the types in this list are Reference types (and inherit from System.Object... except, of course, for object which is the System.Object object):"

System.Object does end up on the heap because it is a reference type, but it does not inherit from System.Object because it IS System.Object (it can't be a supertype of itself).
Reply | Email | Modify 
Value Types and Pointers always go where they were declared. by Paul On October 7, 2008
It's nice to see this properly stated!
Reply | Email | Modify 
Excellent Explanation.. by Charanjot On January 22, 2009
Thank you very much for giving such a wonderful and excellent explanation about Stack and Heap with examples. I didn't find such a health article about memory management. Thanks a lot....
Reply | Email | Modify 
Very Good on by bala On July 6, 2009
Hey its good.
Reply | Email | Modify 
Tracking Heap-ing and Stack-ing? by Jeff On August 31, 2009

Hi Matthew Cochran,
 
Is there a way to track specifically how much Stack-ing and Heap-ing is currently in use?

I would like to checkout what is going on within the Stack and Heap (where, what, and how much memory) that is used during a specific event.

Thanks

Reply | Email | Modify 
Stack vs Heap awesome article... by Manish On September 12, 2009
Thanks Matthew very good article.
Reply | Email | Modify 
Thanks by Tarik On October 15, 2009
Thanks for this really well-written article. It really helped me a lot maybe more than you was expecting during writing. Thanks...
Reply | Email | Modify 
Great Article by Luis On February 4, 2010
Thanks Matthew Cochran this is a great and well explained article. the drawings helps a lot to understand.

Keep the good work!
Reply | Email | Modify 
This article gives a clear picture of Heap and stack in a simple way by john On May 14, 2010
This article gives a clear picture of Heap and stack in a simple way.I liked it..
 
Thanks
 Mathew
Reply | Email | Modify 
Query by Veenu On June 7, 2010
Hi Matthew!

Can you please give me a basic idea about how the memory is configured with Stack and Heap, means is the  Stack and Heap only the logical entities, or we can recognize while having a look at memory that where is stack and where is heap, and which is affecting the memory speed more??
Reply | Email | Modify 
Clear Example by arun On July 8, 2010
Thanks for the good example with a clear pictorial representation
Reply | Email | Modify 
Value Vs Reference Type by Akhil On October 9, 2010
Hi.... I would like to know how the C# will decides that the variable will be created on the Stack or Heap. How its decides ?? Whether Its depends from where its derives System.ValueType or System.Object ????

Akhil
Reply | Email | Modify 
Sort of correct but not really... by Dave On October 22, 2010

  1. Reference and value types that are local variables can also be enregistered by the JIT and thus, technically, do not exist on either the Stack or the Heap; instead, they are placed into a CPU register for faster access.  Whether or not a variable is enregistered is determined by the JIT at runtime and can only be performed if the assembly was compiled with optimizations turned on.
  2. A garbage collection is only triggered under 4 cases:
    • When a memory allocation is requested and the GC determines that it does not have enough space available for the requested allocation.  The *exact* algorithm for how this takes place is proprietary to Microsoft.  However, high-level flowcharts about this process can be found on the internet.
    • GC.Collect() is called - bad, bad, bad...don't ever do this! This should only be used for debugging scenarios. The GC "self-tunes" itself for collections while your app is running. This is based on how your app allocates memory and adjusts its collection algorithm accordingly. Once you call GC.Collect(), you basically "reset" the GC to start its tuning all over again!
    • Memory pressure on the OS is detected. This does not mean memory pressure within your app. On a 32-bit process, you are limited to 2GB of virtual address space. Your app has to share this 2GB with CLR structures like memory for loading the CLR Types, GC stores some info there, and other memory taken by the OS for your app to run. By the time all is said and done, you have approximately 1.2GB for your memory allocations (this varies but not by much). Therefore, it is very easy to get an "OutOfMemoryException" even though you may have plenty of physical memory available.
    • A "rude app domain unload"

The important takeaway here is that your app may hold onto a huge amount of memory for an extended period of time until the next memory allocation request is made.  Depending on your apps this could be seconds, minutes, hours, or days....

Reply | Email | Modify 
simple question by lorna On November 26, 2010
hi,
sticking with the basics, can you explain what happens if this line is added to your example:

MyInt j;

does that allocate any memory (maybe just memory on the stack for a pointer/reference?)
Reply | Email | Modify 
thanks. by Raja On December 4, 2010
is heap is pointer?
Reply | Email | Modify 
General by Shivanand On July 4, 2011
Hey Matthew, Thank you very much for posting this article... I honestly tell you that, i am a beginner in this programming field but after reading this article... many of my concepts which i was not understanding since a long time have been cleared... This is one of the best articles i have ever read... Once again thanks for posting. Regards, Shivanand Arur.
Reply | Email | Modify 
Stack is confusing by Sam On July 24, 2011
Thank you, Matthew. I first learned x86 assembler in about 1988 so I understand about stacks. I also can understand that stacks can be very confusing for beginners. I hope this helps beginners and obviously it does. I think one point that would help is to explain that the interneded purpose (at the machine level) of stacks is different from it's use in higher-level software such as C# and C++. At the assembler level, it is clear why it is called a stack; I think that the use of the stack in C# makes the meaning of "stack" as clear as mud, as you say.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.