search
HomeBackend DevelopmentC#.Net TutorialMemory management of C# value types and reference types

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.


Statement
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
C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.