Six important. NET Concepts "Turn"

Source: Internet
Author: User

Introduction

This article would 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 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 are hampered due to boxing and unboxing, with a sample code.

Watch My videos on various topics like design patterns, WCF, WWF, WPF, LINQ, Silverlight, UML, SharePoint, Azure, VSTS , and a lot more: clickhere.

can also catch me on my trainings Here .

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

What goes inside when are 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's a simple explanation of what happens in the memory, but depending on the data type, your variable is allocated th At type of memory. There is types of memory allocation:stack memory and heap memory. In the coming sections, we'll try to understand these and the types of memory in more detail.

Stack and Heap

In order to understand stacks 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    New Class1 ();}

It's a three line code, let's understand line from line how things execute internally.

      • Line 1: When the executed, the compiler allocates a small amount of memory in the stack. The stack is responsible-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 the stack as a series of compartments or boxes put on top of each of the other. Memory allocation and de-allocation is do using LIFO (last on first out) logic. In other words memory are allocated and de-allocated at only one end of the memory, i.e., top of the stack.
      • Line 3: On line 3, we had created an object. When the executed it creates a pointer on the stack and the actual object are 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. The Heap is used for dynamic memory allocation.

One more important point to note this is reference pointers was allocated on stack. The statement, Class1 cls1; does not allocate memory Class1 for a instance of, it is 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: Now finally the execution control starts Exiting the method. When it passes the end control, it clears all the memory variables which is assigned on the stack. In and words all variables which is related to int data type is de-allocated in ' LIFO ' fashion from the stack.

The big Catch–it did not de-allocate the heap memory. This memory is later de-allocated by the garbage collector.

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

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

Value types and reference types

Now then we have understood the concept of Stack and Heap, it's time to understand the concept of value types and Referenc E types. Value types is 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 was assigned to another the integer data type with name j . Both These memory values is allocated on the stack.

When we assign int int the value to the other value, it creates a completely different copy. In other words, if you change either of them, the other does not a change. These kinds of data types is called as ' Value types '.

When we create a object and when we assign a object to another object, they both point to the same memory location as SH Own in the below code snippet. So when we assign obj obj1 to, they both point to the same memory location.

In other words if we are them, the other object is also affected; This is termed as ' Reference types '.

So which data types is ref types and which are value types?

The. NET depending on the data type, the variable are either assigned on the stack or the heap. ' String ' and ' Objects ' is reference types, and any other. NET primitive data types is assigned on the stack. The figure below explains the same in a more detail manner.

Boxing and Unboxing

Wow, are you having given so much knowledge and so what's the use of it in actual programming? One of the biggest implications is to understand the performance hits which is incurred due to data moving from stack to He AP and vice versa.

Consider the below code snippet. When we move a value of type to reference type, data was moved from the stack to the heap. When we move a reference type to a value type, the data was 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's termed ' Boxing ' and the reverse is termed ' 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. The figure below demonstrates the same.

performance implication of boxing and unboxing

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

The boxing function is executed in 3542 ms while without boxing, the code is executed in 2477 Ms. In and other words try to Avoid boxing and unboxing. In a project where you need boxing and unboxing, the use of it when it ' s absolutely necessary.

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

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

Source Code

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

License

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

From Shivprasad Koirala

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.