Fifty methods of optimizing C# program

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

A, field properties instead of accessible

1,.NET data binding only supports data binding properties can be obtained, using data binding.,

2,You can use the lock add multithreading support in the properties of the get and set access value.   

Two, readonly (runtime constants) and const (compile time constants)

1,Const can be used only for primitive types, enum, string, and the readonly can be any type,

2,Const at compile time will replace specific constant, so that if the reference while using the const and readonly two kinds of values, the readonly change again will change the original intention of the design, this is the need to re compile the change program, to refer to the new constant value.

3,Const than readonly high efficiency, but lost the flexibility of application.   

Three, is and as

1,Both are types of conversion at run time, the as operator can only be used with reference types, is can use value and reference types,

2,The usual practice is to determine the type of is, and then the conversion operator selection using as or strong type (conversion operater defined) selectively.   

Four, ConditionalAttribute instead of #if #endif conditional compilation

1,ConditionalAttribute is only used in the method level, the other such as type, add attribute is invalid; while the #if #endif is not restricted by this,

2,ConditionalAttribute can add multiple compiled conditions or (OR) operation, while #if #endif can add and (AND) [here can be defined as a separate symbol],

3,ConditioanlAttribute definitions can be placed in a separate method, makes the program more flexible.   

Five, provide the ToString () method

1,Can be more friendly way to provide users with information,

2,Use the IFormatter.ToString () method provides a more flexible customization, if you add the IFormatProvider and ICustomFormatter interface is customized message output more meaningful.   

Six, the difference between value and reference types.

1,Value types do not support polymorphic, suitable for storing application data, and references to support polymorphism, applicable to define the behavior of your application,

2,The array is defined as the value types can significantly improve program performance,

3,Value types are less heap memory debris, garbage and indirect access time, its return in the process is to copy the way, avoid exposing the internal structure to external,

4,Value type used in the following scenarios: type of duty is mainly used for data storage; public interface defined entirely by some data members access attributes; never subclass; never polymorphic behavior.   

Seven, value types as much as possible for the type constants and atomicity

1,To make our code easier to write and maintain,

2,Three strategies: initialization constants in the construction; the factory method; auxiliary construct a variable (such as StringBuilder).   

Eight, to ensure that the 0 worth effective state

1,Values default state type should be 0,

2,Enumeration types of 0 should not be invalid state; the FlagsAttribute should ensure that 0 values for the effective state,

3,The empty string in the string is empty can return a string.Empty.   

Nine, a variety of equal representation relation judgment

1,ReferenceEquals()Judgment reference equality, need two is to return the true refer to the same object,

2,Static Equals () method for reference to judge, then the value type judgment,

3,For reference types can determine the use value semantics using override the Equals () method,

4,Override the Equals () method should override the GetHashCode () method, while providing operater== (operation).   

Ten, understand the GetHashCode () method

1,GetHashCode()Only used in hash * * defined key hash based value, such as HashTable or Dictionary,

2,GetHashCode()Should follow the three rules: two equal the corresponding object should return the same hash code; it shall is an example of invariant; hash function should generate a random distribution among all the integers.   

Eleven, give priority to the use of the foreach loop

1,Foreach can eliminate the compiler of for cycle on the array bounds checking,

2,The loop variable foreach is read-only, and there is an explicit conversion, throwing exceptions in object * * object type is not correct,

3,Foreach uses * * need: have public GetEnumberator () method; explicit implementation of the IEnumberable interface; implementation of the IEnumerator interface,

4,Foreach can bring the benefits of resource management, because if the compiler can determine the IDisposable interface, can be used to optimize the try… finally block,   

Twelve, better than the default field initialization assignment statement

1,The default value type field life will be initialized to 0, a reference type is initialized to the null,

2,The same object is initialized repeatedly will reduce the efficiency of code,

3,The field initialization in the constructor for exception handling.   

Thirteen, using a static constructor to initialize static member

1,Static constructors in any methods of a class, before the execution variable or property access,

2,Static fields will also run in a static constructor before, at the same time static constructors for exception handling.   

Fourteen, use the constructor chain (in.NET 4 with optional parameters to solve this problem)

1,Using this to initialize the job to another constructor, base calls the base class constructor,

2,Sequential operation instances of the type: the static field is all set to 0; perform static field initializers execute static constructors; base class; implementation of the current type static constructor,

All instance fields set to 0; executive instance field initializer; perform the appropriate base class instance constructor; the execution of the current instance of the type constructor.   

Fifteen, using the using and try/finally statements to clean up resources

In the IDisposable interface (Dispose) by GC.SuppressFinalize method () can inform the garbage collector does not perform the end of operation.   

Sixteen, to minimize memory garbage

1,Distribution and destroy objects a on the heap to spend additional processor time,

2,To reduce the number of allocated objects skills: enhance local variables often used as field; provide a kind of commonly used example, used to store Singleton objects to express specific types.

3,String operation complicated with StringBuilder.   

Seventeen, try to reduce the package

1,Focus on one type of implicit conversion to System.Object, types should not be substituted for System.Object type at the same time value,

2,Using interfaces instead of using type can avoid packing, type from the interface to value, and then by calling the interface member.   

Eighteen, the standard Dispose model

1,The use of non memory resources, it must have a finalizer, the garbage collector does not end in memory object which is completed, will achieve the finalizer object is added to the end of the queue, and the garbage collector will start a new thread to run finalizers on these objects, this defensive into way because if the user forgets to call Dispose () method, the garbage collector will always call the finalizer method, which can avoid unmanaged memory resources are not caused by the release of memory leak problem,

2,Use the IDisposable.Dispose () method to do the work of four aspects: the release of all unmanaged resources; release all managed resources; setting a state marker to indicate whether has implemented Dispose (); GC.SuppressFinalize (this) to cancel the call object finalization,

3,Add a protected virtual method Dispose types require polymorphic (), derived by override this method to release their tasks,

4,In the type of IDisoposable interface, even if we don't need a finalizer should also implement a finalizer.   

Nineteen, the definition and implementation of interface is better than the type of inheritance

1,Unrelated types can together to achieve a common interface, and realize the interface more easily than inheritance,

2,The interface is stable, he will encapsulate a set of functions in an interface, as the contract of other types, and the base may be carried out with the passage of time extension.   

Twenty, distinguish between implementing interfaces and overriding virtual methods

1,To implement an interface in the base class, the derived class need to use new to hide the use of the base class method,

2,The method can be the base class interface declared as virtual, then the derived class implementation.   

Twenty-one, the use of commissioned express callback

1,A delegate object itself does not provide any exception, so any multicast delegate invocation will end the call chain,

2,Through the display output invoking the delegate chain on each delegate targets can avoid a multicast delegate returns only the last delegation.   

Twenty-two, use the definition of the external interface event

1,Shall be declared the common event, let the compiler to create the add and renmove methods as we,

2,Use the System.ComponentModel.EventHandlerList container to store the event processor complexity, contains a large number of events in the type can be used when he to hide all events.   

Twenty-three, avoid returning references to internal class objects

1,Since the value type object access will create a copy of the object, so the definition of a value type attribute will not change the internal state of the object type,

2,Constant types can avoid change object state,

3,Defines the interface will restrict access to a subset of the internal state so as to minimize the destruction of objects,

4,Defines a wrapper object to another object access,

5,Hope the client code to change the internal data elements can be achieved Observer mode, so that the object can be calibrated or corresponding changes to the.   

Twenty-four, prefer declarative to imperative programming

To avoid the possibility of making mistakes in multiple similar hand coded algorithms, and provide clear and readable code.   

Twenty-five, as far as possible types for type serializable

1,Types that do not UI controls, window or form, should make the type support serialization,

2,In addition to deserialize the NonSerializedAttribute attribute can be realized through IDeserializationCallback OnDeserialization () method to load default values,

3,In the version control can flexibly control the use of ISerializable interface, while providing a serialization constructor initializes the object according to the data stream, in the implementation also requires the abnormal SerializationFormatter license,

4,If you need to create a derived class will need to provide a method for linking the derived class uses.   

Twenty-six, realize the ordering relationship using IComparable and IComparer interface

1,IComparable interface is used to realize the natural ordering relation types, comparison operators four overloaded, can provide an overloaded version of the CompareTo () method, to accept the specific types as parameters,

2,IComparer is used to provide a sort of relationship different from IComparable, or provide us with the type itself said no ordering relation implementation.   

Twenty-seven, avoid the ICloneable interface

1,For value types never need to support the ICloneable interface, use the default assignment can be,

2,For the base class might need to support the ICloneable interface, should create a protected copy constructor for it, and shall avoid support IConeable interface.   

Twenty-eight, avoid the mandatory conversion operators

By using the constructor instead of conversion operators can make the conversion work becomes clearer, the temporary object used in the converted, easily lead to some weird BUG.   

Twenty-nine, consider using the new modifier only when the new result of the accumulation of problems   

Thirty, implementation of CLS compatible as possible assembly

1,Create a compatible program set to follow two rules: the assembly parameters used by all public and protected members and return types must be compatible with the CLS; any is not compatible with the CLS of the public and protected members must have a CLS compatible alternatives,

2,Can implement interfaces explicitly to avoid CLS compatible type checking, CLS compatibility and members of the CLSCompliantAttribute will not check private.   

Thirty-one, implementation method for short and concise as possible

1,The JIT compiler to compile method as a unit, is not does not invoke the method is compiled by JIT,

2,If will replace the Case statement in the long Switch code into one by one, then the JIT compiler saves the time will increase exponentially,

3,Local variables are short and choose a few can optimize the use of registers,

4,Control branches within the method less, JIT compiler, the easier it will be to variables into registers.   

Thirty-two, the realization of small size as possible, high cohesive assemblies

1,Public class all and common base class into a number of assemblies, to provide tools function into the same assembly for the public, the public interface related packaged into their own assembly, finally processing horizontal position throughout the application class,

2,Create two kinds of components in principle: a small and polymerization, with a particular function of the program set, another is big and wide, including the shared assemblies.   

Thirty-three, visibility limit type

1,Use the interface to expose types of functions, so that we can more easily create inner classes, and not limit them in assembly availability,

2,The public type exposes the less, the future expansion and change the implementation have more choice.   

Thirty-four, create a large particle size Web API

This is the frequency and load on the machine between the transactions are reduced to a minimum, the operation and the fine-grained execution on the server to perform.   

Thirty-five, rewriting is superior to the event handler

1,An event handler throws an exception, the other processors on the chain of events will not be invoked, and virtual method does not override the,

2,Rewrite than the associated event processor is much more, the event handler to iterate the entire request list, it takes up more CPU time,

3,Events can response at run time, has more flexibility, can be on the same event correlation of multiple response,

4,Current regulation is a derived class of event processing is good, to rewrite the way.   

Thirty-six, the reasonable use of the.NET runtime diagnosis

1,System.Diagnostics.Debug\Trace\EventLog provides all the tools needed to add a program to run diagnostic information, EventLog applications can provide entrance to the system event log,

2,Finally, don't write your own diagnostic library,.NET FCL has a core library we need.   

Thirty-seven, use the standard configuration mechanism

1,.NET framework of the System.Windows.Application class defines the attributes to establish universal configuration path for us,

2,Application.LocalAppDataPath and Application.userDataPath will generate the local catalog data and user data path name,

3,Don't write data in the ProgramFiles and Windows in the system directory, this position requires a security permission higher, don't expect the user has write permissions.   

Thirty-eight, customization and support data binding

1,BindingMananger and CurrencyManager the two object to implement the data transmission between the controls and data sources,

2,The advantage of using data binding: binding data than to write their own code easier; it should be for a range of text data outside the — — other display properties can also be bound; for the Windowos Forms data binding can handle multiple controls and check the relevant data synchronization source,

3,The object does not support the desired properties, the objects shielding current, then add a desired object to support data binding.   

Thirty-nine, use.NET authentication

1,There are five kinds of controls in ASP.NET to verify the effectiveness, can use a new class of CustomValidator authentication is derived to increase their,

2,Windows verification to System.Windows.Forms.Control.Validating to write an event handler.   

Forty, according to the need to choose the right**

1,The array has two obvious defects: adjust the size cannot be dynamically resize very time consuming;,

2,ArrayList mixed characteristics of one-dimensional arrays and linked lists, Queue and Stack is a special array based on Array,

3,When the program is more flexible to add and delete items, can make a more robust * * type, when creating a simulation * * class, should be the indexers and the IEnumberable interface.   

Forty-one, DataSet is better than the custom structure

1,DataSet has two shortcomings: the interaction between the use of XML serialization mechanism of DataSet and non.NET code is not very good; DataSet is a very common container,

2,The strongly typed DataSet breaks the design more rules, the development efficiency is much higher than that of their preparation looks more elegant design.   

Forty-two, utilize attributes to simplify reflection

Through the design and Realization of property, forcing developers to use them to the statement can be dynamic type used, methods and attributes, can reduce the application run-time errors, improve user satisfaction.   

Forty-three, avoid excessive use of reflection

1,Invoke members to use parameters and return values are System.Object, type conversion at run time, but the possibility of a problem is more,

2,Interface so that we can get a more clear, more maintainable system, reflection is a very powerful late binding mechanism, the.NET framework uses it to realize the data bound Windows control and Web control.   

Forty-four, create the application specific exception classes

1,The only reason for different exception classes is to allow users to easily take different approaches to different error in the preparation of catch processor,

2,There may be different when the repair behavior, we should only exception class to create a wide variety of, through all the constructors provide exception support, exception classes can be created for the application function complete, use the InnerException attribute to all error messages generated kept lower level error conditions.   

Forty-five, priority exception safety guarantees

1,The strong exception guarantee provides the best balance to recover from exceptions and exception handling in operation between the simplified, because the exception and interrupt, the state of the program remain unchanged,

2,Do defensive copy to modify data, defensive copying the data is modified, the operation may throw an exception, the temporary copy and the original object exchange,

3,Terminator, Dispose () method and principal target object bound should ensure they will never throw an exception under any circumstances.   

Forty-six, to minimize the interoperability

1,Interoperability has three aspects: the price data in the managed heap and the unmanaged heap among listed cost, switching between managed and unmanaged code cost, for developers and development of hybrid environment to work,

2,The use of blittable types in interop can be copied back and forth in the managed and unmanaged environments, and is not influenced by the internal structure of objects,

3,Use the In/Out feature to ensure the most appropriate unnecessary repeated copying, by declaring how data are listed to improve performance,

4,Use COM Interop to achieve the most simple way interoperability and COM components, using P/Invoke to call Win32 API, or use the C++ /CLR compiler switch to mix both managed and unmanaged code,   

Forty-seven, give priority to the safety code

1,As far as possible to avoid access unmanaged memory, isolated storage can not prevent from managed code and trusted user access,

2,The assembly when running on Web can consider to use isolated storage, when some algorithms need higher security permissions, should be those code is isolated in a separate assembly.   

Forty-eight, master the related tools and resources

1,Use NUnit to build an automated unit test (integrated in VS2010.),

2,The FXCop tool will get the assembly code of IL, and with the mixed coding rules and best practices for comparative analysis, the final report breaches of the law,

3,ILDasm is a IL disassembly tool, can help us understand the details,

4,Shared Source CLI is a.NET framework includes the kernel and the implementation of C# compiler source code.

Forty-nine, prepare for C#2.0 (this rule has little significance, after all, have now reached 4 )

Fifty, familiar with ECMA standards

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Allen at November 14, 2013 - 1:18 PM