www.codeproject.com articles 76153 6 important net concepts stack heap value types re

7
× highlights off Not quite what you are looking for? You may want to try: OpenNxSerialization A Very Simple Persistent Cache in a COM+ Component 8,662,161 members and growing! Email Password Sign in Join Lost password? Home Articles Quick Answers Discussions Learning Zones Features Help! The Lounge dotnet framework concepts Article Browse Code Stats Revisions (5) Alternatives » Platforms, Frameworks & Libraries » .NET Framework » General Licence CPOL First Posted 27 Apr 2010 Views 192,540 Bookmarked 298 times 6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing. By Shivprasad koirala | 13 Feb 2012 | Unedited contribution .NET1.0 .NET1.1 .NET2.0 SQL2000 SQL2005 VS.NET2003 VS2005 SQL-CE C#1.0 C#2.0 , + 6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and Unboxing. Part of The SQL Zonesponsored by See Also More like this More by this author 4.89 (175 votes) 6 important .NET concepts: -Stack, heap, Value types, reference types, boxing and Unboxing. Introduction What goes inside when you declare a variable? Stack and Heap Value types and reference types So which data types are ref type and value type? Boxing and Unboxing Performance implication of Boxing and unboxing Source code This video explains the concept of boxing and unboxing and it also shows the performance implications caused by the same. Introduction This article will explain 6 important concepts Stack , heap , value types , reference types , 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. Related Articles Page 1 of 7 6 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U... 14-04-2012 http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

Upload: sudip-ray

Post on 14-Oct-2014

64 views

Category:

Documents


0 download

TRANSCRIPT

×

highlights off

Not quite what you are looking for? You may want to try:

• OpenNxSerialization• A Very Simple Persistent Cache in a COM+ Component

8,662,161 members and growing! Email Password Sign in Join Lost password?

Home Articles Quick Answers Discussions Learning Zones Features Help! The Lounge dotnet framework concepts

Article Browse Code Stats Revisions (5) Alternatives

» Platforms, Frameworks & Libraries » .NET Framework » General

Licence CPOL

First Posted 27 Apr 2010

Views 192,540

Bookmarked 298 times

6 important .NET concepts: - Stack,

heap, Value types, reference types,

boxing and Unboxing.By Shivprasad koirala | 13 Feb 2012 | Unedited contribution

.NET1.0 .NET1.1 .NET2.0 SQL2000 SQL2005 VS.NET2003 VS2005 SQL-CE C#1.0 C#2.0 , +

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

Part of The SQL Zonesponsored by

See Also

• More like this

• More by this author

4.89 (175 votes)

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

Unboxing.

Introduction

What goes inside when you declare a variable?

Stack and Heap

Value types and reference types

So which data types are ref type and value type?

Boxing and Unboxing

Performance implication of Boxing and unboxing

Source code

This video explains the concept of boxing and unboxing and it also shows the performance implications caused by the same.

Introduction

This article will explain 6 important concepts Stack , heap , value types , reference types , 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.

Related Articles

Page 1 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

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.

Stack and Heap

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

Collapse | Copy Code

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.

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

Page 2 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

(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 “GARBAGE COLLECTOR”.

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 needs static type memory. If the requirement is of dynamic memory it’s allocated on a heap or else it goes on a stack.

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

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 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

Page 3 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

‘Value types’.

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’.

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.

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

Page 4 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-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 its termed as ‘Boxing’ and the vice versa is termed as ‘UnBoxing’.

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.

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 project you always need boxing and unboxing , use it when it’s absolutely necessary.

Page 5 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

Article Top Sign Up to vote Poor Excellent Vote

Search this forum Go

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

Currently I have not put a source code for unboxing but the same hold true for the same. You can write the same and experiment it by using stopwatch class.

Source code

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

License

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

About the Author

Shivprasad koirala

Architect

http://www.questpond.com

India

Member

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers

Comments and Discussions

You must Sign In to use this message board. (secure sign-in)

Profile popups Noise Medium Layout Normal Per page 10 Update

Refresh First PrevNext

Member 4733806 8:29 9 Apr '12

onurag19 22:03 8 Apr '12

beginner2011 16:45 20 Mar '12

GentlemanK 21:39 5 Mar '12

Petr Abdulin 19:24 4 Mar '12

karthy Udhaykumar 20:18 27 Feb '12

ramanayadavs 0:27 27 Feb '12

fran_hemida 10:27 24 Feb '12

Riz Thon 14:07 20 Feb '12

Shivprasad koirala 3:12 4 Apr '12

Last Visit: 18:00 31 Dec '99 Last Update: 0:06 14 Apr '12 12 3 4 5 6 7 8 9 10 11 Next »

������ ������ ������ ������ ������

Excellent tutorial...

My vote of 5

My vote of 5

My vote of 5

My vote of 5

My vote of 5

My vote of 5

My vote of 5

Nice article, but is stack vs heap that important? [modified]

Re: Nice article, but is stack vs heap that important?

Page 6 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...

Permalink | Advertise | Privacy | MobileWeb01 | 2.5.120412.3 | Last Updated 14 Feb 2012

Article Copyright 2010 by Shivprasad koiralaEverything else Copyright © CodeProject, 1999-2012

Terms of Use

General News Suggestion Question Bug Answer Joke Rant Admin

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

Layout: fixed|fluid

Page 7 of 76 important .NET concepts: - Stack, heap, Value types, reference types, boxing and U...

14-04-2012http://www.codeproject.com/Articles/76153/6-important-NET-concepts-Stack-heap-...