Mining performance optimization Scenarios from the C # garbage collection (GC) mechanism

Source: Internet
Author: User

Gc,garbage Collect, Chinese meaning is garbage collection, refers to the system of memory allocation and recovery management. Its impact on the performance of the system is not to be underestimated. Let's talk about GC optimization today, it's not about concepts and theories, it's about things that are practical. With regard to concepts and theories, just make a brief explanation, and you can see the official Microsoft documentation.

First, what is a GC

The GC, in its name, is garbage collection, which is, of course, just memory. Garbage Collector (garbage collector, also a GC without confusion) takes the root of the application and iterates through all the objects that the application dynamically allocates on the heap [2], by identifying whether they are referenced to determine which objects are dead, Which still needs to be used. Objects that are no longer referenced by the application's root or other objects are dead objects, known as garbage, that need to be recycled. That's how the GC works. To implement this principle, the GC has several algorithms. The more common algorithms are reference Counting,mark sweep,copy collection and so on. The current mainstream virtual system. NET Clr,java VMS and rotor are all using the Mark sweep algorithm. (This section is from the network)

. NET's GC mechanism has such two problems:

First, the GC is not able to release all resources. It does not automatically release unmanaged resources.

Second, the 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 invoke to release unmanaged resources. Use statements can simplify resource management.

Ii. managed resources and unmanaged resources

Managed resources are referred to as. NET resources that can be reclaimed automatically, primarily the memory resources allocated on the managed heap. The collection of managed resources does not require manual intervention, and the. NET runtime is recycled in a suitable call to the garbage collector.

Unmanaged resources are referred to as. NET does not know how to recycle resources, the most common type of unmanaged resources is to wrap the operating system resources of objects such as files, Windows, network Connections, database connections, brushes, icons and so on. This type of resource, the garbage collector calls the Object.Finalize () method when it cleans up. By default, the method is empty, and for unmanaged objects, you need to write code in this method that reclaims the unmanaged resources so that the garbage collector correctly reclaims the resources.

In. NET, the Object.Finalize () method cannot be overloaded, and the compiler automatically generates the Object.Finalize () method based on the destructor of the class, so for classes that contain unmanaged resources, you can place the code that frees the unmanaged resources in the destructor.

Iii. An example of GC optimization

Under normal circumstances, we do not need to control GC these things, but the GC is not real-time, so when our resources are used, the GC when the recovery is also uncertain, so there will be some such as memory leaks, memory shortage situation, such as we deal with a large file about 500M, After use, the GC does not immediately clean up to free up memory, because the GC does not know if we are going to use it, so it waits, first, to deal with something else, and after a while it finds that it is no longer used, and then cleans up and frees up memory.

Here are some of the functions used in the GC:

Gc. SuppressFinalize (this); The common language runtime is requested not to invoke the finalizer of the specified object.

Gc. Gettotalmemory (FALSE); retrieves the number of bytes currently considered to be allocated. A parameter that indicates whether this method can wait for a shorter interval to return so that the system reclaims garbage and the finalization object.

Gc.  Collect (); Enforces instant garbage collection for all generations.

GC Operating mechanism

  Before writing the code, let's start with the GC operating mechanism. As you know, the GC is a background thread that periodically looks for objects and then calls the Finalize () method to consume him, we inherit the IDispose interface, call the Dispose method, destroy the object, and the GC doesn't know. The GC still calls the Finalize () method, and the Object.Finalize () method in. NET cannot be overloaded, so we can use destructors to prevent duplicate releases. After we have called the Dispose method, there is also a call to the Gc.suppressfinalize (this) method to tell the GC that there is no need to call the Finalize () method of these objects.

Below, we create a new console program, add a factory class, let him inherit from the IDispose interface, the code is as follows:

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> ();      Stitching strings, creating some memory garbage public      void Makesomegarbage ()      {for         (int i = 0; i < 50000; i++)         {            sb. Append (i.ToString ());         }      }      When the class is destroyed, the destructor      ~factory ()      {         Dispose (false) is called;      }      public void Dispose ()      {         Dispose (true);      }      protected virtual void Dispose (bool disposing)      {         if (!disposing)         {            return;         }         SB = null;         Gc. Collect ();         Gc. SuppressFinalize (this);}}}   

Only inherit from the IDispose interface, use this class to use the using statement, and write the following code in the Main method:

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)/1024x768);         }         Console.WriteLine ("After GC total memory is {0} KBs."), GC. Gettotalmemory (FALSE)/1024x768);                  Console.read ();}}}   

Run the result as follows, you can see the resource run Makesomegarbage () function after the memory consumption of 1796KB, released into 83Kb.

Code run Mechanism:

  We wrote the Dispose method and the destructor, so when were they called? Let's break down the breakpoint on two different methods. Debug run, you will find the first to go to the Dispose method above, know that the program runs out of the destructor, that is because we call the Gc.suppressfinalize (this) method, if you remove this method, you will find the first to go to the Dispose method, Then the destructor is left. So, we can tell that if we call the Dispose method, the GC will call the destructor to destroy the object, freeing the resource.

Four, when should call Gc.collect

In order to let you see the effect, I show the Call of the Gc.collect () method, let the GC immediately free memory, but frequent calls to the Gc.collect () method will reduce the performance of the program, unless some operations in our program occupy a large amount of memory needs to be released immediately before the call can be displayed. Here are the instructions in the official documentation:

GC is provided by the garbage collection GC class. Collect method, you can use this method to give your application a certain degree of direct control over the garbage collector. In general, you should avoid invoking any recycling methods to let the garbage collector run independently. In most cases, the garbage collector has an advantage in determining the best time to perform a collection. However, in some infrequently occurring situations, forced recycling can improve the performance of your application. GC is used in this case when there is a significant reduction in the amount of memory used on a certain point in the application code. The Collect method may be more appropriate. For example, an application might use a document that references a large number of unmanaged resources. When your application closes the document, you are fully aware that the resources used by the document are no longer needed. For performance reasons, it is meaningful to release these resources all at once. For more information, see GC. Collect method.
Before the garbage collector performs a collection, it suspends all threads that are currently executing. If the GC is called multiple times unnecessarily. Collect, this can cause performance problems. You should also be careful not to place code that calls Gc.collect on points that the user can call frequently in the program. This may weaken the role of the optimization engine in the garbage collector, and the garbage collector can determine the best time to run a garbage collection.

Reference: Http://stackoverflow.com/questions/538060/proper-use-of-the-idisposable-interface

Mining performance optimization Scenarios from the C # garbage collection (GC) mechanism

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.