Home > Backend Development > C#.Net Tutorial > Memory management of C# value types and reference types

Memory management of C# value types and reference types

巴扎黑
Release: 2016-12-20 11:50:41
Original
1770 people have browsed it

In this blog, we will focus on how to improve performance during the software development process. This is a deep-seated problem in the software development or research and development process. This article mainly explains how calculations work in the process of writing our software code from two aspects: memory allocation and memory recycling. Here you can understand the process and methods of memory management so that you can pay attention to it and utilize it in future software development.

Value types include: int, float, double, bool, structure, reference, variables representing object instances

Reference types include: classes and arrays; more special reference types string, object

Generally: value type storage In the stack (excluding value types contained in references, such as value fields of classes, reference fields in classes, elements of arrays, which are stored in the regulated heap with references); reference types are stored in the regulated heap Why the heap is said to be a controlled heap will be discussed in detail below.

A few concepts:

Virtual memory: On a 32-bit computer, each process has 4G of virtual memory.

Regulated heap (managed heap): regulated by whom? The garbage collector, of course, is the garbage collector. How to manage it will be discussed below?

Useless unit collector: In addition to compressing the managed heap, updating the reference address, the garbage collector also maintains the information list of the managed heap, etc.

Regarding the storage of value types, first look at the following code:

{

int age=20;

double salary=2000;

}

The two variables defined above, int age, tell the compiler that they need to be given to me Allocate 4 bytes of memory space to store the age value, which is stored on the stack. The stack is a first-in, last-out data structure, and the stack stores data from high-order addresses to low-order addresses. The computer register maintains a stack pointer, which always points to the free space address at the bottom of the stack. When we define a value of type int, the stack pointer decrements by four bytes of the address; when the variable goes out of scope, the stack The pointer accordingly increments the address by four bytes. It just moves the stack pointer up and down, so the performance of the stack is quite high.

Let’s take a look at the storage of reference types, let’s look at the code first:

{

Customer customerA;

customerA=new Customer(); //Assume that the Customer instance occupies 32 bytes

}

The above code The first line first declares a Customer reference, the name of the reference is customerA, and allocates storage space for this reference on the stack. The size of the storage space is 4 bytes, because it only stores one reference, and the reference pointed to is It is the space address where the Customer instance will be stored. Note that customerA does not point to a specific space at this time, it just allocates a space.

During the execution of the second line, the .net environment will search the managed heap to find the first unused, continuous 32-byte space allocated to the instance of the class, and set customerA to point to the top position of this space (heap The space is used from low to high). When a reference variable goes out of scope, the reference in the stack becomes invalid while the instance remains in the managed heap until the garbage collector cleans it up.

Careful readers here may have some questions. When defining a reference type, does the computer have to search the entire heap to find a memory space large enough to store the object? Will this be very inefficient? What if there is not enough continuous space? This is about "custody". The heap is managed by the garbage collector. When the garbage collector is executed, .net releases all objects that can be released, compresses other objects, and then combines all free space and moves it to the top of the heap to form a continuous block and update it at the same time. References to other mobile objects. If there is another object definition, you can quickly find a suitable space. It seems that the managed heap works similarly to the stack. It allocates and reclaims space through heap pointers.

The above has talked about the management process and methods of .net's memory space allocation. Next, let's talk about the memory recycling process. When it comes to cleaning up resources, we have to mention two concepts and three methods.

Two concepts are: managed resources and unmanaged resources.

Managed resources are managed by the CLR (Common Language Runtime) of the .net framework; unmanaged resources are not managed by it.

The three methods are: Finalize(), Dispose(), Close().

1. Finalize() is a destructor method that clears unmanaged resources.

Defined in the class:

public ClassName{

~ClassName()

{

//Clean up unmanaged resources (such as closing files and database connections, etc.)

}

}

Its features Yes:

1. Operational uncertainty.

It is managed by the garbage collector. When the garbage collector works, this method will be called.

2. High performance overhead.

The way the garbage collector works is that if the object executes the Finalize() method, the first time the garbage collector executes it, it will be placed in a special queue; the object will not be deleted until the second execution.

3. The definition and call cannot be displayed, and the definition is in the form of a destructor method.

Based on the above characteristics, it is best not to execute the Finalize() method unless the class really needs it or it is used in combination with the other two methods.

2. The Dispose() method can clear all resources that need to be cleared, including managed and unmanaged resources.

is defined as follows:

public void Dispose()

{

//Clean up the resources that should be cleaned up (including managed and unmanaged resources)

System.GC.SuppressFinalize(this); //This sentence is very important, and the reasons will be explained below.

}

Its features:

1. Any client code should explicitly call this method to release resources.

2. Due to the first reason, a backup is generally required, and this backup is usually played by the destructor method.

3. The class that defines this method must inherit the IDisposable interface.

4. The syntax keyword using is equivalent to calling Dispose(). When using using, it calls the Dispose() method by default. Therefore, classes using using must also inherit the IDisposable interface.

The Dispose() method is more flexible and releases resources immediately when they are no longer needed. It is the final disposal of the resource, calling it means that the object will eventually be deleted.

3. Close() method, which temporarily disposes the status of resources and may be used in the future. Generally handles unmanaged resources.

is defined as follows:

public viod Close()

{

//Set the status of unmanaged resources, such as closing files or database connections

}

Its features:

Set the status of unmanaged resources Setting, usually closing the file or database connection.


Let’s write a comprehensive and classic example below, using code to demonstrate the function of each part: (To save trouble, this example is made up from the Internet, just explain the problem, what do you think. In We should thank the original author of the code for writing such a classic and easy-to-understand code. We have benefited a lot!

Dispose(true);

System.GC.SuppressFinalize(this);

// The above line of code is to prevent the "garbage collector" from calling the destructor method in this class

// " ~ResourceHolder() "

// Why should we prevent it? Because if the user remembers to call the Dispose() method, then

// "Garbage Collector" does not need to "unnecessarily" release "unmanaged resources" again

/ / If the user doesn't remember to call it, let the "garbage collector" help us to "do the unnecessary thing" ^_^

// It doesn't matter if you don't understand what I said above, I have a more detailed explanation below!

}

protected virtual void Dispose(bool disposing)

{

if (disposing)

{

// Here is the user code snippet to clean up "managed resources".

}

// Here is the user code snippet to clean up "unmanaged resources". Here is the actual execution code of the destructor method. In order to prevent the client code from forgetting to call the Dispose() method, a backup was made.

}

~ResourceHolder()

{

Dispose(false); // This is to clean up "unmanaged resources"

}

}

If you don't understand the above code, Be sure to read the following explanation carefully, it is a classic, you will regret it if you don’t read it.

Here, we must be clear that the user needs to call the method Dispose() instead of the method Dispose(bool). However, the method that actually performs the release work here is not Dispose(), but Dispose(bool)! Why? What? Look carefully at the code. In Dispose(), Dispose(true) is called, and when the parameter is "true", the function is to clean up all managed resources and unmanaged resources; you must still remember what I said earlier, " "The destructor method is used to release unmanaged resources." So since Dispose() can complete the work of releasing unmanaged resources, what is the purpose of the destructor method? In fact, the role of the destructor method is just a "backup" !

Why?

To put it formally, any class that implements the interface "IDisposable", as long as the programmer uses the object instance of this class in the code, sooner or later the Dispose() method of this class must be called. At the same time, if the class contains non- If managed resources are used, unmanaged resources must also be released! Unfortunately, if the code to release unmanaged resources is placed in the destructor method (the above example corresponds to "~ResourceHolder()"), then the programmer wants to call this section It is impossible to release the code (because the destructor method cannot be called by the user, but can only be called by the system, to be precise, the "garbage collector"), so everyone should know why the above example "cleans up the user code of unmanaged resources" "Section" is in Dispose(bool), not ~ResourceHolder()! Unfortunately, not all programmers are always careful to remember to call the Dispose() method. In case the programmer forgets to call this method, the managed Of course there is no problem with the resources. Sooner or later there will be a "garbage collector" to collect them (it will just be delayed for a while), but what about the unmanaged resources? It is not under the control of the CLR! Could it be that the unmanaged resources it occupies can never be released? Of course not! We still have a "destruction method"! If you forget to call Dispose(), then the "garbage collector" will also call the "destruction method" to release unmanaged resources! (One more nonsense, if If the programmer remembers to call Dispose(), then the code "System.GC.SuppressFinalize(this);" can prevent the "garbage collector" from calling the destructor method, so that there is no need to release "unmanaged resources" one more time) So we You are not afraid that programmers forget to call the Dispose() method.


Related labels:
c
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template