[Design principles and suggestions] constructor and analysis object

Source: Internet
Author: User

Well-structured and destructed objects, and object lifecycle control can be greatly improvedProgramPerformance, reduce GC pressure, and reduce the chance of bugs.

This article is relatively simple, mainly based on experience. You may already know a lot of things, but you may not know. I hope you will discuss it together.

 
 

1. If possible, avoid static Constructor (also become a Type constructor)

    • Performance (however, because a class's static constructor only executes once, this is not a big problem)
    • The static constructor should not throw an exception

2. If possible, the constructor should be as lightweight as possible

    • The constructor should only construct an object, rather than executing a lot of initialization and other operations.
    • If there is a heavyweightCode, Use the static method to create, for example, webrequest. Create

3. Common sense: When a constructor is called, the constructor of the parent class is called first.
 

4. parameters required for a class should be placed in the input parameters of the constructor (or the create method)

    • The main reason is the logic and guarantee of the execution sequence.
    • Do not assign values to each attribute after the construction is complete.

5. If you want to initialize private members in sequence, perform the (or create method) operation in the constructor)

    • Although CLR is currently a private member initialized from top to bottom, the initialization sequence of future versions is not guaranteed.
    • Some third-party tools will change when the code is automatically formatted.

6. Virtual methods should not be called in Constructors

    • Http://msdn.microsoft.com/zh-cn/library/ms182331 (vs.90). aspx

7. Using this () and base () can facilitate mutual calls between constructors.
 

8. Do not construct objects without any need (although it may be optimized out)

 
Dataset DS =NewDataset ();
DS = sqlhelper. executedataset ("Select * From Table1");

 

9. Shorten the object lifecycle with more performance considerations (performance is not considered in most programs)

    • Initialization as late as possible
    • Destroy objects as early as possible
    • Minimal Scope
    • If the object may be reused, study the object resurrection of GC.
    • A tip
    • Singletonclass Item1 =Null;
      For(IntI =0; I <100; I ++)
      {
      Singletonclass item2 =Null;//There is no difference between the two statements and the statement is optimized.
      }

10. If the object implements idisposable

    • Use using or directly call dispose
    • Some System Objects implement close. In fact, dispose () is called inside close ()

11. If you want to implement an idisposable

Simple implementation

ClassConstructordemo: idisposable

{
Public VoidDispose ()
{
Dispose (True);
GC. suppressfinalize (This); // Tell CLR not to call finalize. This is a very performance-consuming method.
}

Private VoidDispose (BoolDisposing)
{
If(! Disposing)
{
//Clear managed resources
}
//Clear unmanaged Resources
}
}

 

Complete implementation http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx

 

12. If you want to implement Singleton

View code

     Public   Class Constructordemo1
{
Private Static Singletonclass Singleton = New Singletonclass ();
// I like this method most for simple classes. It is annoying if the constructor is not enough.
// Don't worry too much about performance issues when initializing only once
// If the singletonclass constructor throws an exception, it will be finished.

Private Constructordemo1 ()
{
}
Public Singletonclass create ()
{
Return Singleton;
}
}

Public Class Constructordemo2
{
Private Static Singletonclass Singleton =Null ;
Private Static Object Asynclock = New Object ();
Private Constructordemo2 ()
{
}
Public Singletonclass create () // You don't need to worry too much about performance when initializing only once. You can handle initialization problems here.
{
If (Singleton = Null )
{
Lock (Asynclock)
{
If (Singleton = Null )
{
Singleton = New Singletonclass ();
}
}
}
Return Singleton;
}
}

Public Class Constructordemo3
{
Private Static Lazy <singletonclass> Singleton = New Lazy <singletonclass> ();
Private Constructordemo3 ()
{
}
Public Singletonclass create ()
{
Return Singleton. value; // 4.0.
}
}

13. Understanding the general principles of GC will help design programs that meet expectations.

    • We recommend that you refer to CLR via C #
    • If you do not want to be GC, put the object on a static member in the simplest way.
    • An example of accidental Resource Recovery
 Using System;
Using System. Threading;
Public Static Class Program
{
Public Static Void Main ()
{
// Note: Run in release mode.
Timer T = New Timer (timercallback, Null , 0 , 2000 );
Console. Readline ();
}
Private Static Void Timercallback (Object O)
{
Console. writeline ( " In timercallback: " + Datetime. Now );
GC. Collect (); // Triggering GC
}
}

14. Generally, no destructor are used to release resources.

    • Microsoft recommends using destructor to release unmanaged resources (such as file and network connections)
    • In my personal suggestion, we recommend that you do not use the destructor, but explicitly Recycle resources (idisposable) because the internal structure is calledFinalize, And the running time of this thing is uncertain... There are also performance problems
View code

     Public  Class Deconstructor
{

// Finalize is not recommended. The main problem is that the call time is uncertain and there are performance problems.
~ Deconstructor ()
{
// Clear code // Will be converted to the following code
}
// Protected override void finalize ()
// {
// Try
// {
// // Clear code
// }
// Finally
// {
// Base. Finalize ();
// }
// }
}

 

15. Do not create a large number of small objects

    • For example, string
    • For example, serialization and deserialization in WCF and WebService

 

 

PS: GC. suppressfinalize is often called in dispose to notify CLR: I will handle it myself. You should not call finalize

PS: GC has workstation and server Modes

PS: GC may also cause memory leakage. Generally, some objects are always referenced and cannot be GC.

PS: GC timeout will also throw outofmemoryexception, not necessarily because there is no memory.

PS: use tools such as dotnettrace to analyze what objects exist in the memory. You can also analyze the performance of constructor and destructor.

PS: Using windbg + SOS to Analyze memory is also good (especially in the production environment)

PS: I personally prefer static methods over instance methods (rather than constructing objects each time), unless it is a design requirement or logically it should be an instance method.

 

Some of the information comes from the Internet, because I am rich. please correct me if you have any mistakes.

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.