6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing.

No.of Views1373
Bookmarked0 times
Downloads 
Votes1
By  questpond   On  02 May 2010 03:05:05
Tag : .NET Frameworks , How to
This article will explain 6 important concepts Stack , heap , by val , by ref , boxing and unboxing. This article starts first explaining what happens internally when you declare a variable and then i
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Content

 

Introduction

What goes inside when you declare a variable?

Stack and Heap

By Val and By ref


So which data types are ref type and value type?

Boxing and Unboxing

Performance implication of boxing and Unboxing

Source code
 

Introduction

This article will explain 6 important concepts Stack , heap , by val , by ref , boxing and unboxing. This article starts first explaining what happens internally when you declare a variable and then it moves ahead to explain 2 important concepts stack and heap. Article then talks about reference types and value types and clarifies some of the important fundamentals around them.

Finally the article concludes by demonstrating how performance is hampered due to boxing and unboxing with a sample code.

Watch my 500 videos on various topics like design patterns,WCF, WWF , WPF, LINQ ,Silverlight,UML, Sharepoint ,Azure,VSTS and lot more @ click here , you can also catch me on my trainings @ click here.
 

 

Image Loading

 

Image taken from http://michaelbungartz.wordpress.com/ 
 

What goes inside when you declare a variable?

When you declare a variable in a .Net application, it allocates some chunk of memory in to the RAM. This memory has 3 things first the name of the variable, second data type of the variable and finally the value of the variable.

That was a simple explanation of what happens in the memory, but depending on what kind of data type your variable is allocated on that type of memory. There are two types of memory allocation stack memory and heap memory. In the coming sections we will try to understand these two types of memory in more details.

 

Image Loading

 

Stack and Heap

In order to understand stack and heap, let’s understand what actually happens in the below code internally.
 

public void Method1()
{
// Line 1
int i=4;

// Line 2
int y=2;

//Line 3
class1 cls1 = new class1();
}

 

It’s a 3 line code so let’s understand line by line how things execute internally.

Line 1:- When this line is executed compiler allocates a small amount of memory in to memory type called as stack. Stack is responsible of keeping track of running memory needed in your application.

Line 2:- Now the execution moves to the next step. As the name says stack it stacks this memory allocation on the top of the first memory allocation. You can think about stack as series of compartment or boxes put on top of each other.

Memory allocation and de-allocation is done using LIFO (Last in first out) logic. In other words memory is allocated and de-allocated at only one end of the memory i.e. top of the stack.

Line 3:- In line 3 we have a created an object. When this line is executed it creates a pointer on the stack and the actual object is stored in a different type of memory location called as ‘Heap’. ‘Heap’ does not track running memory it’s just pile of objects which can reached at any moment of time. Heap is used for dynamic memory allocation.

Exiting the method (The fun):- Now finally the execution control starts exiting the method. When it passes the end control it clears all the memory variables which are assigned on stack. In other words all variables which are related to ‘int’ data type are de-allocated in ‘LIFO’ fashion from the stack.

The BIG catch – It did not de-allocate the heap memory. This memory will be later de-allocated by “GARBAGE COLLECTOR”. 

 

Image Loading

 

Now many of our developer friends must be wondering why two types of memory, can’t we just allocate everything on just one memory type and we are done.

If you look closely in the above method ‘int’ variables where allocated on the stack because compiler already had an idea of how much (-2,147,483,648 to 2,147,483,647) data storage they need. When it came to objects compiler did not know internally how much space will be needed so it allocated the same on the heap.

In other words if the data size is uknown and dynamic they are allocated on the heap and upfront if the data size is know they are allocated on the stack.

Image taken from http://michaelbungartz.wordpress.com/ 

 

Image Loading

 

By Val and By ref

Now that we have understood the concept of ‘Stack’ and ‘Heap’ it’s time to understand the concept of value types and reference types.

Value types are types which hold both data and the memory on the same location. While a reference type has a pointer which points to the memory location.

Below is a simple integer data type with name ‘i’ whose value is assigned to an other integer data type with name ‘j’. Both these memory values are allocated on the stack.

When we assign the ‘int’ value to the other ‘int’ value it creates a complete different copy. In other word if you change either of them the other does not change. These kinds of data types are called as ‘Value types’.
  

Image Loading

 

When we create an object and when we assign one object to the other object, they both point to the same memory location as show in the below code snippet. So when we assign ‘obj’ to ‘obj1’ they both point to the same memory location.

 

In other words if we change one of them the other object is also affected this is termed as ‘Reference types’. 

 
Image Loading

 

So which data types are ref type and value type?

In .NET depending on data types the variable is either assigned on the stack or on the heap. ‘String’ and ‘Objects’ are reference types and any other .NET primitive data types are assigned on the stack. Below figure explains the same in a more detail manner.  

Image Loading

 

Boxing and Unboxing

WOW, you have given so much knowledge, so what’s the use of it in actual programming. One of the biggest implications is to understand the performance hit which is incurred due to data moving from stack to heap and vice versa.

Consider the below code snippet. When we move a value type to reference type the data is moved from the stack to the heap. When we move reference type to a value type the data is moved from the heap to the stack.

This movement of data from the heap to stack and vice-versa creates incurs lot of performance hit.

When the data moves from value types to reference types its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.
 

 

Image Loading

 

If you compile the above code and see the same in ILDASM you can see in the IL code how ‘boxing’ and ‘unboxing’ looks, below figure demonstrates the same.

 

Image Loading

 

Performance implication of boxing and Unboxing

In order to see how the performance is impacted we ran the below two functions 10,000 times. One function has boxing and the other function is simple. We used a stop watch object to monitor the time taken.

The boxing function was executed in 3542 MS while unboxing was executed in 2477 MS. In other words until much needed try to avoid boxing and unboxing.

With the same article the sample code is attached which demonstrates this performance implication.
 

 

Image Loading

 

Source code

Attached with article is a simple code which demonstrates how boxing and unboxing creates performance implications. You can download the source code from here

 

 
Sign Up to vote for this article
 
About Author
 
questpond
Occupation-
Company-
Member Type-Expert
Location-Not Provided
Joined date-24 Jun 2009
Home Page-
Blog Page-
 
 
Other popularSectionarticles
    Structure in C# allows us to group the variables and methods. Its some what similar to classes but that's not true there are no. of difference between class and structure. But here in this post I am not going to discuss about that, here I am going to explain how to Initialize Structure.
    Published Date : 10/Feb/2011
    In this article i will explain about extension method and how to create in .NET
    Published Date : 28/Jan/2011
    The scope of this document is to describe integration of SAP Web Services and Microsoft .NET using Microsoft Visual Studio.
    Published Date : 18/Aug/2010
    Let us start this article by a small chat between customer and developer. Scenario 1 Customer: - How’s your application performance? Subjective developer: - Well it’s speedy, it’s the best …huuh aaa ooh it’s a like rocket. Scenario 2 Customer: - How’s your application performance? Quantitative developer: - With 2 GB RAM , xyz processor and 20000 customer records the customer screen load in 20 secs. I am sure the second developer looks more promising than the first developer. In this
    Published Date : 10/May/2010
    Ask any developer which is the best place in a .NET class to clean unmanaged resources?, 70% of them will say the destructor. Although it looks the most promising place for cleanup it has a huge impact on performance and memory consumption. Writing clean up code in the destructor leads to double GC visits and thus affecting the performance multifold times. In order to validate the same we will first start with bit of theory and then we will actually see how GC algorithm performance is impacte
    Published Date : 06/May/2010
Comments
By:srinivasu dandamudiDate Of Posted:2/23/2011 11:08:14 AM
RE:
very nice, clear explanation. Thanks
By:kirtiDate Of Posted:5/4/2010 6:08:40 AM
Great affort
Great work
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top