[Reprint favorites] 6 important. Net concepts:-stack, heap, value types, reference types, boxing and unbo

Source: Internet
Author: User

From: Code project

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
 

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 moreClick here, You can also catch me on my trainings @Click here.
 

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

What goes inside when you declare a variable?
 

When you declare a variable in. 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
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 (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 users 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 '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 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 executedin 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.

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.
 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.