Click here to Skip to main content
16,021,432 members
Articles / Programming Languages / C#

Six Important .NET Concepts: Stack, Heap, Value Types, Reference Types, Boxing, and Unboxing

Rate me:
Please Sign up or sign in to vote.
4.90/5 (434 votes)
23 Jun 2021CPOL7 min read 1.6M   3K   659   249
An introduction to stack, heap, value types, reference types, boxing, and unboxing
In this article, you will learn about what happens internally when you declare a variable followed by an explanation of two important concepts: stack and heap. The article then talks about reference types and value types and clarifies some of the important fundamentals around them. Finally, you will see a demonstration of how performance is hampered due to boxing and unboxing, with sample code.

Table of Contents

In case you do not want to read my complete article , you can watch the below video on Stack vs Heap | Boxing vs Unboxing | Value Type vs Reference Type .

Image 1

 

For further reading, do watch the below interview preparation videos and step by step video series.

Introduction

This article will explain six important concepts: stack, heap, value types, reference types, boxing, and unboxing. This article starts explaining what happens internally when you declare a variable and then it moves ahead to explain two important concepts: stack and heap. The article then talks about reference types and value types and clarifies some of the important fundamentals around them.

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

Image 2

What Goes Inside When You Declare a Variable?

When you declare a variable in a .NET application, it allocates some chunk of memory in the RAM. This memory has three things: the name of the variable, the data type of the variable, and the value of the variable.

That was a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated 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 detail.

Image 3

Stack and Heap

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

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

    // Line 2
    int y=2;

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

It’s a three line code, let’s understand line by line how things execute internally.

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 1: When this line is executed, the compiler allocates a small amount of memory in the stack. The stack is responsible for keeping track of the 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 top of the first memory allocation. You can think about stack as a series of compartments or boxes put on top of each other.
  • Line 3: In line 3, we have 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 ‘Heap’. ‘Heap’ does not track running memory, it’s just a pile of objects which can be reached at any moment of time. Heap is used for dynamic memory allocation.

One more important point to note here is reference pointers are allocated on stack. The statement, Class1 cls1; does not allocate memory for an instance of Class1, it only allocates a stack variable cls1 (and sets it to null). The time it hits the new keyword, it allocates on "heap".

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 the garbage collector.

Image 4

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, primitive data types are not complex, they hold single values like ‘int i = 0’. Object data types are complex, they reference other objects or other primitive data types. In other words, they hold reference to other multiple values and each one of them must be stored in memory. Object types need dynamic memory while primitive ones needs static type memory. If the requirement is of dynamic memory, it’s allocated on the heap or else it goes on a stack.

Image 5

Value Types and Reference Types

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 memory on the same location. 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 another 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 completely different copy. In other words, if you change either of them, the other does not change. These kinds of data types are called as ‘Value types’.

Image 6

When we create an object and when we assign an object to another object, they both point to the same memory location as shown 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 7

So Which Data Types Are Ref Types and Which Are Value Types?

In .NET, depending on the data type, 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. The figure below explains the same in a more detailed manner.

Image 8

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, data is moved from the stack to the heap. When we move a 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 a performance hit.

When the data moves from value types to reference types, it is termed ‘Boxing’ and the reverse is termed ‘UnBoxing’.

Image 9

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

Image 10

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 without boxing, the code was executed in 2477 ms. In other words, try to avoid boxing and unboxing. In a project where you need boxing and unboxing, use it when it’s absolutely necessary.

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

Image 11

Currently, I have not included the source code for unboxing but the same holds true for it. You can write code and experiment it using the stopwatch class.

About the Source Code

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

History

  • 27th April, 2010: Initial version
  • 24th June, 2021: Updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
GeneralMy vote of 5 Pin
sudheer muhammed15-Nov-12 0:23
sudheer muhammed15-Nov-12 0:23 
Questionnicely done! Pin
lookitstony30-Oct-12 7:48
lookitstony30-Oct-12 7:48 
GeneralMy vote of 5 Pin
maheshbisht29-Oct-12 23:09
maheshbisht29-Oct-12 23:09 
QuestionNice Article Pin
arunthangavel22-Oct-12 21:02
arunthangavel22-Oct-12 21:02 
GeneralExcellent! Pin
zhengwb18-Oct-12 21:29
zhengwb18-Oct-12 21:29 
GeneralMy vote of 5 Pin
soulprovidergr18-Sep-12 4:14
soulprovidergr18-Sep-12 4:14 
GeneralMy vote of 5 Pin
Raveesh15-Sep-12 6:20
Raveesh15-Sep-12 6:20 
GeneralMy vote of 4 Pin
Arun Babu A15-Sep-12 1:29
Arun Babu A15-Sep-12 1:29 
very good article written in an easily
understandable way
QuestionNicely presented. Pin
KChandos9-Aug-12 5:28
professionalKChandos9-Aug-12 5:28 
Questionboxing or unboxing Pin
gagan sawaliya9-Aug-12 2:54
gagan sawaliya9-Aug-12 2:54 
GeneralMy vote of 5 Pin
gagan sawaliya9-Aug-12 2:49
gagan sawaliya9-Aug-12 2:49 
GeneralMy vote of 5 Pin
GuyThiebaut23-Jul-12 9:41
professionalGuyThiebaut23-Jul-12 9:41 
GeneralMy vote of 5 Pin
Alecoder23-Jul-12 3:49
Alecoder23-Jul-12 3:49 
GeneralMy vote of 5 Pin
massiah310012-Jul-12 23:41
massiah310012-Jul-12 23:41 
Questionvisit Pin
AnnieCalvert12-Jul-12 2:50
AnnieCalvert12-Jul-12 2:50 
QuestionMy Vote of 5! Pin
akosidab20-Jun-12 21:01
akosidab20-Jun-12 21:01 
GeneralMy vote of 4 Pin
brigano17-Jun-12 21:51
brigano17-Jun-12 21:51 
GeneralMy vote of 5 Pin
Mohammad A Rahman22-May-12 17:44
Mohammad A Rahman22-May-12 17:44 
GeneralMy vote of 5 Pin
kumuda.t21-May-12 21:42
kumuda.t21-May-12 21:42 
Question[My vote of 2] inaccuracies or poor wordings. Pin
Jay R. Wren21-May-12 11:40
Jay R. Wren21-May-12 11:40 
GeneralMy vote of 5 Pin
Shilpa Gurnani16-May-12 2:31
Shilpa Gurnani16-May-12 2:31 
GeneralMy vote of 5 Pin
Oshtri Deka15-May-12 22:13
professionalOshtri Deka15-May-12 22:13 
QuestionHow string datatype allocates memory? Pin
Ravi Mori15-May-12 21:32
Ravi Mori15-May-12 21:32 
AnswerRe: How string datatype allocates memory? Pin
Ravi Mori15-May-12 23:14
Ravi Mori15-May-12 23:14 
QuestionMy vote of 5 Pin
shanmugarajaa15-May-12 20:40
shanmugarajaa15-May-12 20:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.