Mining performance optimization schemes from the C # garbage collection (GC) Mechanism

Source: Internet
Author: User

Mining performance optimization schemes from the C # garbage collection (GC) Mechanism
GC, Garbage Collect, Chinese meaning is Garbage collection, refers to the distribution and recovery management of memory in the system. Its impact on system performance cannot be underestimated. Let's talk about GC optimization today. Here we will not focus on concepts and theories, but mainly on practical things. Here is a brief description of concepts and theories. For details, refer to the official Microsoft documentation. 1. What is GC? Its name is garbage collection. Of course, this is only for memory. Garbage Collector (Garbage Collector, which also becomes GC without confusion) uses the root of the application to traverse all objects dynamically allocated by the application on Heap [2], identify whether they are referenced to determine which objects are dead and which still need to be used. The object that is no longer referenced by the root of the application or another object is the dead object, that is, the so-called garbage, which needs to be recycled. This is how GC works. To achieve this principle, GC has multiple algorithms. Common algorithms include Reference Counting, Mark Sweep, and Copy Collection. Currently, the mainstream virtual systems. net clr, Java VM and Rotor both adopt the Mark Sweep algorithm. The gc mechanism of. NET has two problems: first, 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 may cause bottlenecks and uncertainty in system performance. With the IDisposable interface, the IDisposable interface defines the Dispose method, which is used by programmers to explicitly call to release unmanaged resources. You can use using statements to simplify resource management. 2. managed resources and unmanaged resources are resources that can be automatically recycled by. NET, mainly memory resources allocated on the managed stack. The collection of managed resources does not require manual intervention. Some. NET runtime Libraries call the Garbage Collector to recycle the resources. Unmanaged resources refer. NET does not know how to recycle resources. The most common type of unmanaged resources are the objects that encapsulate operating system resources, such as files, windows, network connections, database connections, image brushes, and icons. This type of resource, the garbage collector will call the Object. Finalize () method during cleaning. By default, the method is empty. For unmanaged objects, you need to write code to recycle unmanaged resources in this method so that the garbage collector can correctly Recycle resources. In. NET, Object. the Finalize () method cannot be overloaded. The Compiler automatically generates an Object based on the class destructor. the Finalize () method. Therefore, for classes that contain unmanaged resources, you can place the code that releases the unmanaged Resources in the destructor. Iii. An example of GC optimization we normally don't need to worry about GC. However, GC is not real-time, so after our resources are used up, it is not certain when GC is recycled, so it will bring some situations such as memory leakage and insufficient memory. For example, we can process a large file of about MB, after the GC is used up, it will not be cleaned up immediately to release the memory, because GC does not know whether it will be used again, so it will wait and process other things first. After a while, only when these things are no longer used can they be cleaned up to release the memory. Next, we will introduce several functions used in GC: GC. SuppressFinalize (this); // do not call the terminator of the specified object during the request for public language runtime. GC. GetTotalMemory (false); // retrieves the number of bytes currently considered to be allocated. A parameter that indicates whether the method can wait for a short interval before returning, so that the system can recycle garbage and terminate objects. GC. Collect (); // force instant garbage collection for all generations. Before writing code, let's talk about the GC running mechanism. As we all know, GC is a background thread that periodically searches for objects and calls the Finalize () method to consume them. We inherit the IDispose interface, call the Dispose method, and destroy the objects, GC does not know. GC still calls the Finalize () method, but in. NET, the Object. Finalize () method cannot be overloaded, so we can use the destructor to prevent repeated releases. After calling the Dispose method, we also call the GC. SuppressFinalize (this) method to tell GC that the Finalize () method of these objects does not need to be called. Next, we will create a console program and add a Factory class to let it inherit from the IDispose interface. The Code is as follows: copy the code using System; using System. collections. generic; using System. linq; using System. text; namespace GarbageCollect {public class Factory: IDisposable {private StringBuilder sb = new StringBuilder (); List <int> list = new List <int> (); // concatenate a string, create some memory spam public void MakeSomeGarbage () {for (int I = 0; I <50000; I ++) {sb. append (I. toString () ;}// when the class is destroyed, Will call the Destructor ~ Factory () {Dispose (false);} public void Dispose () {Dispose (true);} protected virtual void Dispose (bool disposing) {if (! Disposing) {return;} sb = null; GC. collect (); GC. suppressFinalize (this) ;}} the copied Code only inherits from the IDispose interface. You can use the Using statement when using this class. Write the following code in the main method: copy the code using System; Using System. collections. generic; using System. linq; using System. text; using System. diagnostics; namespace GarbageCollect {class Program {static void Main (string [] args) {using (Factory f = new Factory () {f. makeSomeGarbage (); Console. writeLine ("Total Memory is {0} KBs. ", GC. getTotalMemory (false)/1024);} Console. writeLine ("After GC total memory is {0} KBs. ", GC. getTotalMemory (false)/1024); Console. read () ;}} copy the code execution result as follows. You can see that the memory usage of the resource after running the MakeSomeGarbage () function is 1796KB, and then it is 83Kb. code Running Mechanism: we have written the Dispose method and the destructor. When will they be called? We break points on the two methods respectively. After debugging and running, you will find that you have gone to the Dispose method first, knowing that the program is not running the destructor, because we have called GC. suppressFinalize (this) method. If this method is removed, you will find that the first Dispose method is followed by the destructor. Therefore, we can know that if we call the Dispose method, GC will call the destructor to destroy the object and release the resource.

Related Article

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.