Stacks, heaps, value types, reference types, boxing and unpacking

Source: Internet
Author: User

What happens in memory when you declare a variable?

When you're in a. NET application when declaring a variable, the first to allocate some memory fast to RAM, it consists of three things, the first is the variable name, the second is the variable data type, the last one is the value of the variable.

This is a very simple explanation, depending on the data type of the variable, there are two types of memory allocations: stack memory and heap memory.

Figure 2 Memory structure after declaring a variable

Stacks (stack) and heaps (heap)

To help understand the stack and heap, let's understand what's going on inside the code below.

  1. Public void Method1 ()
  2. {
  3. Line 1
  4. int i=4;
  5. Line 2
  6. int y=2;
  7. Line 3
  8. Class1 cls1 = new Class1 ();
  9. }

There are only three lines of code inside this method, and I'll explain what's going on in the inner line.

First line: When the row is executed, the compiler allocates a small chunk of memory called the stack, which is responsible for keeping track of the memory that the application needs to run.

The second line: Now execution moves to the next step, as the stack name implies, when this memory allocation is stacked at the top of the previous memory allocation, you can interpret the stack as a sequence of layers of compartments or boxes.

Memory allocations and deallocation use LIFO (last in first out, LIFO) logic, in other words, memory is allocated and deallocated at the end of memory, such as the top of the stack.

Third line: In the third row we create an object that executes the row, it creates a pointer on the stack, the real object is to store a different type of memory allocation (called a heap), the heap does not track the running memory, it is just the accumulation of objects, and the heap is used for dynamic memory allocation.

Exit method (interesting): After executing the last line of code, it is time to exit this method, when it passes the end control, it clears all memory variables allocated to the stack, in other words, all the variables associated with the INT data type are deallocated from the stack in a LIFO manner.

However, the heap memory allocation is not lifted, and this portion of memory is deallocated through the garbage COLLECTOR (garbage collector).

Figure 33 The internal memory operation of the line code

Many people may now ask why they want to set up two types of memory allocation. Is it not possible to complete memory allocations in a form of memory allocation?

If you look closely, you'll know that the int variables are allocated on the stack, because the compiler already knows how much data they can store (2,147,483,648 to 2,147,483,647), and when it comes to objects, the compiler doesn't know how much internal space is needed. Therefore, the same size of space is allocated on the heap.

In other words, if the data size is not known or is dynamically changing, it needs to be allocated to the heap, and if the data size is deterministic, it is allocated on the stack.

Figure 4 is assigned to the stack when the variable size is known and not known when the variable size is assigned to the heap

Value types and reference types

A value type refers to a type that holds both data and memory in the same location, whereas a reference type points to a memory location with a pointer. The following is a simple integer data type named I, whose value is given by another integer data type named J, and the two memory values are based on the stack allocation.

When we assign an int value to another int value, it creates a completely different copy, in other words, if you modify one of the values without causing another value to change, the data type is called the value type.

Figure 5 Value type: One value change does not cause another value to change

When we assign an object to another object, they point to the same memory location, as shown, when we assign obj to obj1, they point to the same memory location. In other words, if we modify one of the objects, another object is affected, and this type is called the reference type.

Figure 6 Reference type: Changes in one object can cause another object to change

Which data type is a value type and a reference type?

In. NET, depending on the data type, variables may be stack-based or heap-based, string and objects are reference types, and others. NET data types are based on stack allocations and are explained in more detail.

Figure 7 corresponds to a reference type and a value type. The data types in net

      This article will explain. NET of six important concepts, they are stack, heap, value type, reference type, boxing and unpacking. First, explain what happens in memory when you declare a variable, then introduce two important conceptual stacks and heaps, then describe the value types and reference types, and at the end of the article use examples to illustrate the effects of boxing and unboxing on performance.

Packing (boxing) and unpacking (unboxing)

Having said so much, how do you use them in actual programming? The biggest problem is figuring out the performance penalty for moving data from the stack to the heap, and vice versa.

As shown, when we move a value type to a reference type, the data is moved from the stack to the heap, and when we move the reference type to the value type, the data is moved from the heap to the stack. Moving data from the stack to the heap, or from the heap to the stack, can result in a significant performance penalty. The process of moving data from a value type to a reference type is called boxing, and moving from a reference type to a value type is called unpacking.

Figure 8 Packing and unpacking process schematic

If you compile the above code in the same ildasm, you will see how the code in IL is boxed and unboxing, as shown in.

Figure 9 Packing and unpacking

Performance impact of boxing and unpacking

To see the impact of the performance, we ran the following two functions 1000 times, as shown in the left-hand function has a boxing unboxing operation, the right function does not, we use a Stopwatch object to monitor the time spent.

Figure 10 Comparison of the execution time of packing unboxing and unboxing unboxing

From what we have seen, it takes 3542 milliseconds to decorate and dismantle the box, and it only takes 2477 milliseconds to disassemble the box, so the effect on the performance is quite large.

Now you're on these two important. Does the net concept all understand?

Stacks, heaps, value types, reference types, boxing and 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.