Effective C # Principle 16: Minimization of garbage

Source: Internet
Author: User
Tags datetime

The garbage collector behaves well in memory management, and it removes objects that are no longer in use in a very efficient way. But no matter how you look at it, it takes more processor time to apply and release a heap-based object than to request and release an object that is not based on the heap memory. You can give some serious performance problems, such as an application allocating too many reference objects within a method.

You shouldn't overload the garbage collector, you can use some simple techniques to reduce the garbage collector's work for the sake of program efficiency. All reference types, even local variables, are allocated on the heap. Local variables of all reference types become garbage immediately after the function exits, and one of the most common "garbage" practices is to request a drawing handle for Windows:

protected override void OnPaint( PaintEventArgs e )
{
 // Bad. Created the same font every paint event.
 using ( Font MyFont = new Font( "Arial", 10.0f ))
 {
   e.Graphics.DrawString( DateTime.Now.ToString(),
   MyFont, Brushes.Black, new PointF( 0,0 ));
 }
 base.OnPaint( e );
}

The OnPaint () function is called very frequently, and each time it is invoked, another font object is generated, and in fact it is exactly the same content. The garbage collector needs to clean these objects every time. It would be incredibly inefficient.

Instead, the Font object is provided as an object member from a local variable, and the same object is reused each time the window is drawn:

private readonly Font _myFont =
 new Font( "Arial", 10.0f );
protected override void OnPaint( PaintEventArgs e )
{
 e.Graphics.DrawString( DateTime.Now.ToString( ),
  _myFont, Brushes.Black, new PointF( 0,0 ));
 base.OnPaint( e );
}

This way your program does not generate garbage at every paint event, the garbage collector's work is reduced, and your program runs a little faster. When you promote a local variable that implements the IDisposable interface to a type member, such as a font, your class should also implement the IDisposable interface. Principle 18 will give you an explanation of how to do it correctly.

When a reference type (the value type doesn't matter) a local variable that is used very frequently in a regular function call, you should elevate it to be a member of the object. That font is a good example. Only commonly used local variables frequent access is a good candidate, not the frequent call is not necessary. You should try to avoid duplicating the creation of the same object, using member variables instead of local variables.

The static property Brushes.black used in the previous example demonstrates another technique that avoids duplicating the creation of similar objects. Use static member variables to create instances of some commonly used reference types. Consider the black brush used in the previous example, and each time you draw something with a black brush, you create and release a large number of black brushes in the program. One of the previous solutions is to add a brush member to each class that expects a black brush, but that's not enough. The program may create a large number of Windows and controls, which will also create a large number of black brushes. NET Framework designers foresee this problem, they create a simple black brush for you so you can reuse it anywhere. The Brushes object contains a number of static brush objects, each with a different common color. Internally, brushes uses the lazy algorithm to create these objects only when you are using them. A simple way to achieve this:

private static Brush _blackBrush;
public static Brush Black
{
 get
 {
  if ( _blackBrush == null )
   _blackBrush = new SolidBrush( Color.Black );
   return _blackBrush;
 }
}

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.