50 ways to improve C # programs and improve program performance

Source: Internet
Author: User
Tags access properties array definition case statement finally block

Transferred from: http://blog.sina.com.cn/s/blog_6f7a7fb501017p8a.html

First, use attributes instead of accessible fields

1,. NET data binding only supports data binding, the use of attributes can obtain the benefits of data binding;

2. The get and set accessors of a property can be used to add multi-threaded support with lock.

Second, ReadOnly (running constant) and const (compile constant)

1, const can only be used for primitive types, enumerations, strings, and readonly can be any type;

2. The const will be replaced with a specific constant at compile time, so if both const and readonly two values are used in the reference, then the re-change of ReadOnly will change the original intention of the design, which requires recompiling the changed assembly to re-reference the new constant value.

3, the const is higher than the readonly efficiency, but loses the application flexibility.

Third, is and as

1. Both are type conversions at run time, and the as operator can only be used in reference types, while is can use values and reference types;

2, the usual practice is to use the is to determine the type, and then choose to use as or a strongly typed conversion operator (with operater defined conversion) selectively.

Iv. ConditionalAttribute instead of # if #endif条件编译

1, ConditionalAttribute only for the method level, the addition of other types, attributes, etc. is invalid; # if #endif则不受此限制;

2. ConditionalAttribute can add multiple compilation conditional or (or) operations, while # if #endif则可以添加与 (and) [can be fully defined here as another separate symbol];

3, Conditioanlattribute definition can be placed in a separate method, making the program more flexible.

V. Provision of the ToString () method

1, can be more friendly way to provide users with detailed information;

2, using the Iformatter.tostring () method to provide more flexible customization, if the addition of IFormatProvider and ICustomFormatter interface is more meaningful custom message output.

Vi. differences in value and reference types

1. The value type does not support polymorphism and is suitable for storing data for application operations, while references support polymorphism, which is suitable for defining the behavior of the application;

2, for the array definition as a value type can significantly improve the performance of the program;

3, the value type has less heap memory fragmentation, memory garbage and indirect access time, its return in the method is copied in the way, to avoid exposing the internal structure to the outside world;

4. The value type is applied in the following scenario: the type of responsibility is mainly used for data storage; The public interface is defined entirely by some data member access properties; There is never a subclass; there is never a polymorphic behavior.

The value types are implemented as constant and atomic as possible

1, make our code easier to write and maintain;

2. Three strategies for initializing constants: in construction; factory methods; Constructs a mutable auxiliary class (such as StringBuilder).

Eight, make sure 0 is worth the valid status

1, the default state of the value type should be 0;

2, enumeration type 0 should not be invalid state, in FlagsAttribute is to ensure that the value of 0 is a valid state;

3. You can return a string if the strings are empty. Empty null string;

Nine, the multi-expression relation of equal judgment

1, ReferenceEquals () to judge the reference is equal, need two is to refer to the same object when the side can return true;

2, the static Equals () method advanced reference judgment and then the value type judgment;

3. For reference type judgment, you can use the override Equals () method when using value semantics;

4. Overriding the Equals () method should also override the GetHashCode () method while providing a operater== () operation.

X. Understanding the shortcomings of the GetHashCode () approach

1. GetHashCode () applies only the hash value of the hash-based set that defines the key, such as Hashtable or dictionary;

2, GetHashCode () should follow the corresponding three rules: two equal objects should return the same hash code; it should be an instance invariant; the hash function should produce a random distribution in all integers;

Xi. use of the Foreach Loop statement first

1. Foreach can eliminate the compiler checking the array boundary of the For loop;

2. The loop variable of foreach is read-only and there is an explicit conversion that throws an exception when the object type of the collection object is not correct;

3. The set used by foreach needs to have a public getenumberator () method, an explicit implementation of the Ienumberable interface, and a IEnumerator interface;

4. Foreach can bring the benefit of resource management, because if the compiler can determine the IDisposable interface can use the optimized try...finally block;

12. Initialization of default fields is better than assignment statements

1, field life by default, the value type is initialized to 0, the reference type is initialized to null;

2, multiple initialization of the same object will reduce the efficiency of code execution;

3. Placing the initialization of a field in the constructor facilitates exception handling.

13. Initializing static members with static constructors

1. The static constructor executes before any method, variable, or property of a class is accessed;

2, static fields will also run before the static constructor, while the static constructor facilitates exception handling.

14, the use of the constructor chain (in. NET 4.0 has been used to solve the problem with optional parameters)

1. Use this to give the initialization work to another constructor, using base to call the base class constructor;

2. The order of operation of the type instance is: Set all static fields to 0, execute static field initializers, execute static constructors of the base class, execute static constructors of the current type;

Set all instance fields to 0, execute the instance field initializer, execute the appropriate base class instance constructor, and execute the instance constructor of the current type.

Using using and try/finally statements to clean up resources

Use Gc.suppressfinalize () in the Dispose () method of the IDisposable interface to notify the garbage collector not to perform the finalization operation.

16. Minimizing Memory waste

1. Allocating and destroying a pair of objects takes additional processor time;

2. Tips for reducing the number of allocated objects: frequently used local variables are promoted to fields; Provides a class for storing singleton objects to express common instances of a particular type.

3. Use StringBuilder for complex string manipulation.

17. Reduce packing and unpacking as much as possible

1, focus on a type to System.Object implicit conversion, and value type should not be replaced with the System.Object type;

2, using interfaces instead of using types can avoid boxing, the value type is implemented from the interface, and then the member is called through the interface.

18. Implement standard Dispose mode

1, using a non-memory resource, it must have a finalizer, the garbage collector will implement a finalizer object after the completion of the memory object without terminating it to the end queue, and then the garbage collector will start a new thread to run the finalizers on those objects. This defensive approach is because if the user forgets to call the Dispose () method, the garbage collector always calls the finalizer method, which avoids the problem of memory leaks caused by unmanaged memory resources not being freed;

2, the use of the IDisposable.Dispose () method requires four aspects of work: release all unmanaged resources, release all managed resources, set a status token to indicate whether Dispose () has been executed ; Call Gc.suppressfinalize (this) to cancel the end operation of the object;

3. Add a protected virtual method to Dispose () for types that require polymorphism, and derive classes to release their tasks by overriding this method;

4. In a type that requires a idisoposable interface, a finalizer should be implemented even if we do not need a finalizer.

19. Define and implement interfaces better than inherited types

1, unrelated types can jointly implement a common interface, and the implementation of the interface is easier than inheritance;

2, the interface is relatively stable, he encapsulates a set of functions in one interface, as other types of implementation contracts, while the base class can be extended over time.

20. Distinguish between interface implementation and virtual method rewriting

1. When implementing an interface in a base class, the derived class needs to use new to hide the use of the base class method;

2, the method of the base class interface can be declared as a virtual method, and then implemented in the derived class.

21. Use delegate to express callback

1, the delegate object itself does not provide any exception capture, so any multicast delegate call will end the entire call chain;

2. The multicast delegate can be prevented from returning only the output of the last delegate by displaying each delegate target on the call delegation chain.

22. Using events to define the external interface

1, should be declared as a common event, let the compiler to create for us the Add and Renmove method;

2. Use the System.ComponentModel.EventHandlerList container to store individual event handlers that can be used to hide the complexity of all events when they contain a large number of events in the type.

23. Avoid returning references to internal class objects

1. Because access to a value type object creates a copy of the object, a property that defines a value type does not change the state of the type object at all;

2, constant type can avoid changing the state of the object;

3. Define the interface to restrict access to a sub-set to minimize the destruction of the internal state of the object;

4. Define a wrapper object to restrict access to another object;

5. You can implement observer mode when you want the customer code to change internal data elements so that the object can validate the changes or respond accordingly.

24. Declarative programming is better than command-type programming

You can avoid the possibility of making mistakes in several similar hand-written algorithms, and provide clear and readable code.

25. Implement the type as serializable as possible

1. Types that are not UI controls, windows, or forms should make the type support serialization;

2, in the addition of NonSerializedAttribute properties of the deserialization can be implemented by implementing the Ideserializationcallback OnDeserialization () method to load the default value;

3, in version control can use the ISerializable interface for flexible control, while providing a serialized constructor to initialize the object according to the data in the stream, when implemented also requires the SerializationFormatter exception license.

4. If you need to create a derived class, you need to provide a hook method for use by derived classes.

26, using IComparable and IComparer interface to achieve sort relationship

1. IComparable interface is used to implement the most natural sort relation for type, overload four comparison operators, can provide an overloaded version of the CompareTo () method, let it accept the concrete type as the parameter;

2. IComparer is used to provide a sort relationship different from icomparable, or to provide us with a sort relationship that the type itself says is not implemented.

27. Avoid ICloneable interface

1, for value type never need to support ICloneable interface using the default assignment operation;

2. For base classes that may need to support the ICloneable interface, create a protected copy constructor for it, and avoid supporting the Iconeable interface.

28. Avoid forced conversion operators

By using a constructor instead of a conversion operator, you can make the conversion work clearer, and because of the temporary objects that are used after the conversion, it is easy to cause some weird bugs.

29. Consider using the new modifier 30 to implement the CLS-compliant assembly as much as possible only if the new version accumulation causes the problem

1. There are two rules for creating a compatible assembly: all public and protected members in the assembly must have a CLS-compliant parameter and return value type, and any public and protected member that is incompatible with the CLS must have a CLS-compliant alternative;

2. You can avoid CLS-compliant type checking by explicitly implementing an interface, and CLSCompliantAttribute does not check the CLS compatibility of private members.

31, as far as possible to achieve a short concise method

1, the JIT compiler to compile the method for the unit, the method is not called will not be JIT compiled;

2. If you replace the code of the case statement in a longer switch with one method, the time saved by the JIT compiler will multiply.

3, the short method and select less local variables can be used to obtain the optimized register;

4. The fewer control branches within a method, the easier the JIT compiler can put variables into registers.

32, as far as possible to achieve small size, high cohesion assembly

1. Put all the public classes and common base classes in some assemblies, and put the tool classes that provide functionality for the public class into the same assembly, package the relevant public interfaces into their own assemblies, and finally deal with classes that are horizontally located in the application;

2, in principle, create two components: a small and aggregated, with a specific function of the assembly, the other is large and wide, containing the common functionality of the assembly.

33. Limit the visibility of types

1, the use of interfaces to expose the type of functionality, you can make it easier for us to create internal classes, without limiting their availability outside the Assembly;

2. The fewer publicly exposed public types, the more choices you have for future extensions and change implementations.

34. Create a large-grained web API

This is where the frequency and load of the trades between machines are minimized, with large operations and fine-grained execution placed on the server execution.

35, rewrite better than event handler

1, an event handler throws an exception, the other processors on the event chain will not be called, and the overridden virtual method will not occur;

2, rewrite is much more efficient than the associated event handler, the event handler needs to iterate over the entire request list, which takes up more CPU time;

3, the event can respond at runtime, with more flexibility, can be associated with multiple responses to the same event;

4, the rule is to deal with a derived class event is, the overriding way is better.

36, reasonable use. NET run-time diagnostics

1. SYSTEM.DIAGNOSTICS.DEBUGTRACEEVENTLOG provides all the tools that the program needs to add diagnostic information to the runtime, eventlog the application that provides the entry can write to the system event log;

2. Finally do not write your own diagnostic library, the. NET FCL already has the core library we need.

37. Use standard configuration mechanism

1,. The System.Windows.Application class for the NET Framework defines the properties that establish a common configuration path for us;

2, Application.localappdatapath and Application.userdatapath will generate the local data directory and the path name of the user data;

3, do not write data in the ProgramFiles and Windows system directories, these locations require higher security permissions, do not expect users to have write permissions.

38. Customizing and supporting data binding

1, Bindingmananger and CurrencyManager the two objects realize the data transmission between the control and the source;

2. The advantage of data binding: Using data binding is much simpler than writing your own code, it should be used in a range other than text data items-Other display properties can also be bound, and for windowos Forms data binding to handle multiple control synchronization checks related data sources;

3. You can support data binding by masking the current object and then adding a desired object when the object does not support the desired property.

39, use. NET authentication

1, ASP. NET has five kinds of controls to verify the validity, you can use CustomValidator to derive a new class to add its own authenticator;

2. Windows authentication requires a sub-System.Windows.Forms.Control.Validating of some event handlers.

40, according to the need to choose the appropriate collection

1, the array has two obvious defects: cannot dynamically adjust the size, the adjustment size is very time-consuming;

2, ArrayList mixed with one-dimensional array and the characteristics of the list, queue and stack are based on an array of special arrays;

3, when the program more flexible add and delete items, you can make a more robust collection type, when you create a class to simulate the collection, you should implement the indexer and ienumberable interface.

41. DataSet is better than custom structure

1. The dataset has two drawbacks: the interaction between a dataset and the non-. NET code using the XML serialization mechanism is not very good; the DataSet is a very generic container;

2. A strongly typed dataset breaks more design rules, and its development efficiency is much higher than the more elegant design it has written.

42, using the characteristics to simplify the reflection

By designing and implementing attribute classes, developers are forced to use them to declare types, methods, and properties that can be used dynamically, reducing application run-time errors and improving software user satisfaction.

43. Avoid excessive use of reflection

1, the invoke member uses the parameter and the return value are System.Object, carries on the type conversion at the run time, but the possibility of the problem also becomes more;

2, the interface allows us to get a clearer, more maintainable system, reflective of a very powerful late binding mechanism. The NET Framework uses it to implement data binding for Windows controls and Web controls.

44. Create a specific exception class for your application

1. The only reason to require different exception classes is to make it easy for users to take different approaches to different errors when writing a catch processor.

2, there may be different repair behavior when we should create a number of different exception classes, by providing all the constructors supported by the exception base class, you can create a fully functional exception class for your application, and use the InnerException property to hold all the error messages generated by lower-level error conditions.

45, preferential selection of abnormal security guarantee

1. Strong exception guarantee provides the best balance between recovering from exception and simplifying exception handling, and the state of the program is left unchanged when the operation is interrupted due to an exception;

2, the data will be modified to make defensive copy, the defensive copy of the data to modify, this intermediate operation may throw an exception, the temporary copy and the original object to Exchange;

3, the finalizer, Dispose () method, and the target method bound by the delegate object should in all cases ensure that they do not throw an exception.

46. Minimize Interoperability

1, interoperability has three aspects of the cost: the enumeration of data between the managed heap and the unmanaged heap, the cost of switching between managed and unmanaged code, and the development of a mixed environment for developers;

2. Using the Blittable type in interop can be effectively replicated back and forth in managed and unmanaged environments, regardless of the internal structure of the object;

3, using the In/out feature to ensure the most appropriate unnecessary multiple copies, by declaring how the data is enumerated to improve performance;

4. Use COM interop to implement interoperability with COM components in the simplest way, using P/invoke to invoke the Win32 API, or to mix managed and unmanaged code with the/clr switch of the C + + compiler;

47, priority to choose the security code

1, as far as possible to avoid access to unmanaged memory, isolated storage does not prevent access from managed code and trusted users;

2. When the assembly is running on the web, you can consider using isolated storage, and when some algorithms do require a higher security license, you should isolate those code in a separate assembly.

48. Master relevant tools and resources

1, the use of NUnit to establish automatic unit testing (integrated in the VS2010);

2. The FxCop tool gets the IL code in the assembly and contrasts it with the interracial coding rules and best practices, and finally reports the violation;

3, ILDASM is an IL disassembly tool, can help us to gain insight into the details;

4. The Shared source CLI is an implementation source that contains the. NET Framework kernel and the C # compiler.

49, to prepare for the c#2.0 (this rule has no meaning now, after all, has now reached 4.0) 50, understand the ECMA standard

50 ways to improve C # programs and improve program performance

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.