Background Overview
When developing client systems in C#, the .net framework itself consumes memory resources, especially on computers such as xp, which are not very high in memory configuration, so memory optimization is required to run smoothly on which low-end computers. If you want to optimize client memory for C# development, you need to understand the following concepts.
Virtual memory
Here we quote the concept of Baidu Encyclopedia: Virtual memory is a technology for memory management of computer systems. It makes the application think that it has continuous available memory (a continuous and complete address space), when in fact, it is usually separated into multiple physical memory fragments, and some are temporarily stored on external disk memory for data exchange when needed. Currently, most operating systems use virtual memory, such as the "virtual memory" of the Windows family; the "switch space" of Linux, etc.
In a word, virtual memory is the memory space virtualized by using disks and physical disks.
Physical memory
Physical memory is relative to virtual memory. Physical memory refers to the memory space obtained through physical memory sticks, while virtual memory refers to dividing a piece of area of the hard disk as memory. The main function of memory is to provide temporary storage for the operating system and various programs when the computer is running. Common physical memory specifications include 256M, 512M, 1G, 2G, etc. Nowadays, with the development of computer hardware, memory specifications with 4G, 8G or even higher capacity have appeared. When physical memory is insufficient, virtual memory can be used instead. In applications, it is naturally the size of the capacity of the memory stick inserted on the motherboard memory slot, as the name suggests. When looking at computer configuration, the main thing we are looking at is this physical memory.
GC garbage collection mechanism
Introduction
Like Java, C# is a language that automatically recycles resources in the system. It recycles system resources through GC (Garbage Collect) in the C# environment. In the basic data types, it is introduced that C# data types are divided into reference types and value types.
The value type is saved on Stack and will be automatically released as the function's execution scope is completed, so this type of resource is not the object that GC cares about. GC garbage collection mainly refers to resources stored on Heap.
There are two problems with the GC mechanism of .NET:
- First of all, GC does not release all resources. It cannot automatically release unmanaged resources.
- Second, GC is not real-time, which will cause bottlenecks and uncertainties in system performance.
GC is not real-time, which can cause bottlenecks and uncertainties in system performance. So with the IDisposable interface, the IDisposable interface defines the Dispose method, which is used by programmers to explicitly call to release unmanaged resources. Using using statements can simplify resource management.
Managed and unmanaged resources
As mentioned above, GC only releases managed resources, so what are managed resources and paid managed resources.
- Managed resources: Managed resources refer to resources that .NET can automatically recycle, mainly referring to memory resources allocated on the managed heap. The recycling of managed resources does not require manual intervention. There is a .NET runtime library that is suitable for calling the garbage collector for recycling.
- Unmanaged resources: Unmanaged resources refer to resources that .NET does not know how to recycle. The most common type of unmanaged resources are objects that wrap operating system resources, such as files, windows, network connections, database connections, brushes, icons, etc. Such resources,
The garbage collector will call the() method when cleaning up. By default, the method is empty, and for unmanaged objects, you need to write code to recycle unmanaged resources in this method so that the garbage collector recycles resources correctly.
- Summary: The releasing of managed resources is done by GC. The release time is not certain. Generally, the system feels that the memory is tight and will urgently recycle resources. If an object wants to be recycled, it must first become garbage. GC determines whether the object and its sub-objects have any valid references. If there is no GC, it is considered garbage. The garbage collection mechanism uses a certain algorithm to obtain resources that have not been referenced or are no longer called. When this garbage reaches a certain amount, the garbage collection mechanism is started again. GC recycling actually calls the destructor. The garbage collection mechanism means you don't need to worry about handling objects you no longer need. What we care about is the release of non-managed resources. There are three generations of objects during garbage collection: 0, 1, and 2. Each generation has its own memory budget, and garbage collection will be called when there is insufficient space. In order to improve performance, they are recycled by generation. After the 0th generation exceeds the budget, the 0th generation objects are recycled, and the surviving objects are promoted to the 1st generation, and so on. It is often possible to recycle the 1st generation once after multiple 0th generation garbage collections.
GC performs garbage collection by the system. The following is the code for forced recycling (do not use this method in non-special cases, as it will affect the system efficiency and weaken the role of the optimization engine in the garbage collector, and the garbage collector can determine the best time to run garbage collection)
//Garbage collection for all generations.(); //Garbage collection for the specified agent.(int generation); //Force garbage collection for zero generation to specified generation at the time specified by the value.(int generation, GCCollectionMode mode);
About SetProcessWorkingSetSize and Memory Free
In applications, some functions are often used to free memory, etc. In fact, memory operation functions should be used with caution, such as SetProcessWorkingSetSize, which people often think of. In fact, for Windows, the system will automatically release memory when the program is idle (such as the program is minimized). When releasing it with memory, it will often cause some inexplicable memory errors, causing unstable applications and systems.
The role of SetProcessWorkingSetSize
Transfer physical memory to virtual memory
- msdn explains: Using this function to set the minimum and maximum running space of the application will only retain the required memory. When the application is idle or the system memory is too low, the operating system will automatically call this mechanism to set the application's memory. Applications can also use VirtualLock to lock a certain range of memory and not be released by the system. When you increase the running space to the application, the physical memory you can get depends on the system, which will cause other applications to reduce performance or the overall performance of the system, which may also cause the operation of requesting physical memory to fail. For example, when establishing a process, thread, and kernel pool, you must be careful to use the function. That is to say, the function does not save memory, but forces the physical memory of the process to be moved to virtual memory.
Disadvantages of SetProcessWorkingSetSize
- Hazards: If the SetProcessWorkingSetSize function is used normally, it is very useful. However, in order to deceive the user's eyes, pressing a large amount of memory into the virtual memory every second or even dozens of milliseconds will bring unpredictable harm. See how this article says: "Because it only temporarily moves the memory occupied by the application to the virtual memory. Once the application is activated or there is an operation request, the memory will be re-occupied. If you force this method to set the memory occupied by the program, it may reduce the system performance to a certain extent, because the system needs to frequently exchange pages between memory and hard disk."
Optimize memory code:
[DllImport("")] private static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max); private void FlushMemory() { (); (); if ( == PlatformID.Win32NT) { SetProcessWorkingSetSize(().Handle, -1, -1); } }
The above is the detailed content of the detailed analysis of c# client memory optimization. For more information about c# client memory optimization, please pay attention to my other related articles!