6 Important one. NET concept stacks, heaps, value types, reference types, boxing, unpacking

Source: Internet
Author: User

Introduced

This article will explain 6 important concepts: stacks, heaps, value types, reference types, boxing, unpacking. This article will explain what happens when you declare a variable and explain in advance two important concepts: stacks and heaps. The article clarifies some important basic information around reference types and value types. A simple example is presented to demonstrate the performance penalty caused by boxing and unpacking.

What happens when you declare a variable?

When you're in. NET application, a small chunk of memory is allocated from RAM, and there are three things in memory: The variable name, the data type, and the value of the variable.

We simply explain what happens in memory, knowing that the allocation of variables in memory depends on the data type. There are two types of memory allocations: stack memory and heap memory. As shown, we will have a clearer understanding of both types of memory.

Heap and Stack

To understand the heap and stack, let's look at how this code works inside.

public void Method1 () {    //Line 1    int i=4;    Line 2    int y=2;    Line 3    Class1 cls1 = new Class1 ();}

Here are three lines of code, let's take a line to explain its internal mechanism.

First line: when this line of code executes, the compiler allocates a small chunk of memory on the stack, which is responsible for tracking the application's running in memory.

second line: now do the next step, as the stack's name says, each time the memory is allocated at the top of the stack, you can think of the stack as a series of boxes stacked up.

The allocation and recycling of memory is achieved through LIFO (LIFO) logic, in other words, the allocation and collection of memory begins at the top.

Third line: in the third row, an object is created, and when this line of code finishes, a pointer is created on the stack to point to the object, and the object is actually stored in another

Different memory locations that are called "heaps". A heap is a collection of objects that can be accessed at any time, and the heap is used for dynamic memory allocation because it cannot track the running of the memory.

It is important to note that the reference pointer is allocated on the stack. Declares Class1 CLS1, and does not allocate memory to the class Class1, it allocates only one CLS1 stack variable (and sets it to null) until it encounters the New keyword, which is allocated on the heap.

Exit method (function): Now we're finally getting out of the execution control method. When it ends the final control, clears all memory variables that are allocated on the stack. In other words, all variables related to the INT data type are recycled from the stack in a "last in, first out" manner.

It is important to note that the heap does not release memory. Instead, it is reclaimed by the garbage collector.

Now many developer friends must want to know why there are two types of memory, we can not just allocate a memory type to achieve everything we do? If you look closely, the basic data types are not complex, they hold a single value, like "int i = 0". The object data types are complex and they reference other objects or other basic data types. In other words, they have pointers to multiple other value references, and each pointer must be stored in memory. The object type requires dynamic memory and the underlying type requires a static type of memory. If the requirement is dynamic memory, it must be allocated on the heap, otherwise allocated on the stack.

Value types and reference types

Now that we know the concept of stacks and heaps, it's time to understand the concepts of value types and reference types. A value type saves both data and memory in the same location, and a reference type has a pointer to the actual memory area.

Through, we can see a type of shaping data called I, whose value is assigned to another shaped data type named J. Their values are stored on the stack.

When we assign a value of type int to another value of type int, it actually creates a completely different copy. In other words, if you change the value of one of these, the other does not change. As a result, these kinds of data types are referred to as "value types".

When we create an object and assign the object to another object, they point to each other in the same area of memory as the code snippet shows. So when we assign obj to obj1, they point to the same area in the heap. In other words, if we change any of them at this point, the other will be affected, which also explains why they are referred to as "reference types".

What are value types and which are reference types?

In. NET, whether a variable is stored in a stack or in a heap depends entirely on the data type to which it belongs. For example: ' String ' or ' Object ' belongs to the reference type, while the other. NET primitive data type is assigned to the stack. is shown in detail in the. NET preset types, which are value types and which are reference types.


Packing and unpacking

Now, you have a lot of theoretical foundation. Now it is time to understand the use of the above knowledge in practical programming. One of the biggest implications of the application is understanding the performance consumption problems that occur when data is moved from the stack to the heap, and vice versa.

Consider the following code snippet, when we convert a value type to a reference type, the data is moved from the stack to the heap. Conversely, when we convert a reference type to a value type, the data is also moved from the heap to the stack.

Whether moving from the stack to the heap or moving from the heap to the stack inevitably has some impact on the system performance.

As a result, two words turned out: The process of converting data from a value type to a reference type is called boxing, and the process of converting from a reference type to a value type is "unboxing."


If you compile the above code and view it in ILDASM (an IL anti-compilation Tool), you will find out what boxing and unboxing are like in the IL code. The IL code generated after the sample code is compiled is shown.

Performance issues for boxing and unpacking

In order to figure out what the performance impact of boxing and unpacking will be, we cycle through the two function methods shown in 10,000 times respectively. There is a boxing operation in the first method, and the other is not. We use a Stopwatch object to monitor the time consumption.

The method with the boxing operation took 3542 milliseconds to complete, and the method without the boxing operation took only 2477 milliseconds, a full 1 seconds. Also, this value increases as the number of cycles increases. In other words, we should try to avoid packing and unpacking operations. In a project, if you need boxing and boxing, carefully consider whether it is absolutely essential to the operation, if not, then try not to.


Although the above code snippet does not show a unboxing operation, the same effect applies to unpacking. You can write code to implement unpacking and test its time consumption through stopwatch.

6 Important one. NET concept stacks, heaps, value types, reference types, boxing, unpacking

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.