Efficient C # Coding optimization,

Source: Internet
Author: User

Efficient C # Coding optimization,

1. foreach VS for statement

Foreach has better execution efficiency than
The average time spent by Foreach is only 30% of that of for. When both for and foreach can be used through the test results, we recommend using a more efficient foreach.
In addition, the write time using for is about 10 times the read time.

2. Avoid using ArrayList

ArrayList performance is low. Any Object to be added to the ArrayList must be enclosed as System. Object. The data retrieved from the ArrayList must be split back to the actual type.
High Performance of generic collection classes. Generic sets are strongly typed.

3. Use the HashTable dictionary set
We recommend that you use HashTable to replace dictionary collections such as StringDictionary, NameValueCollection, and HybridCollection when storing a small amount of data.

4. Declare constants for string containers
Declare constants for string containers. Do not directly enclose strings in double quotation marks (")" to avoid constant creation and release of string objects in memory. This improves the access efficiency of string objects.
// Avoid
MyObject obj = new MyObject ();
Obj. Status = "Active ";
// Recommended
Const string c = "Acive ";
MyObject obj = new MyObject ();
Obj. Status = c;

5. Use String. Compare () to Compare strings
Do not use UpperCase or LowerCase to convert the case of a string before comparison.
Use String. Compare () to ignore String case sensitivity for comparison.
String strTemp = "Active ";
If (String. Compare (strTemp, "active", true) = 0 ){
Optional lt. Write ("Equal ");
}

6. concatenate strings using StringBuilder
1. The String class object is immutable (read-only). The re-assignment of the String object is essentially re-creating a new String object and assigning a new value to the object.
2. system. text. stringBuilder maintains a string of the same length as Capacity (which can be considered as a character array). When the string of the Capacity length is insufficient to accommodate the result string, stringBuilder opens up a new memory area with the Capacity calculated by the preceding rules, copies the original string to the new memory area, and then performs the operation. The original string area is handed over to GC for recovery. Therefore, memory allocation and recovery are also involved. It is best to estimate the required Capacity when using StringBuilder, and use this Capacity to initialize Capacity to improve performance. StringBuilder cannot ensure that all instance members are thread-safe. Although many threads are added to the type definition, to ensure thread security, you must manually implement the thread synchronization mechanism.

7. XPathDocument reading XML files
If you only want to read the data of an XML object, you can use the read-only XPathDocument instead of XMLDocument to improve the performance.

8. Avoid declaring variables in the body of the loop. Declare variables in vitro and initialize variables in the body of the loop.
// Avoid
For (int I = 0; I <10; I ++ ){
SomeClass obj = new SomeClass ();
//...
}
// Recommended
SomeClass obj = null;
For (int I = 0; I <10; I ++ ){
Obj = new SomeClass ();
//...
}

9. Capture the specified exception
When an Exception is caught, a specific Exception class should be used to capture the Exception, and the scope of the Exception should be defined in a descending order. Do not use general System. Exception
Private void Find (object obj ){
Try {
Console. write (obj. ToString ());
}
Catch (ArgumentNullException ane)
{//... }
Catch (ArgumentException AE)
{//... }
Catch (SystemException se)
{//... }
Catch (Exception e)
{//... }
}
Do not use Exception to control the process. Capture exceptions is well known for performance loss, so it is best to avoid exceptions.

10. Use using and try/finally to clear Resources
. The. NET platform provides GC (Garbage Collection) for Memory Management, which is responsible for automatically releasing managed resources and memory recovery. However, it cannot release unmanaged resources, at this time, we must provide our own methods to release the unmanaged resources allocated in the object.
To use an unmanaged resource type, you must implement the IDisposable interface's Dispose method to release data accurately.
When you use a typed resource with the Dispose method, you should call the Dispose method when it is used up to release unused resources in time.
Using or try/finally can better ensure that the Dispose method is called in a timely manner.

11. avoid abuse of reflection
Reflection is a waste of performance, so we should avoid abuse of reflection.
Causes of performance impact:
When reflection is used to call the type or trigger method and access field attributes, CLR needs to do more work: Verify parameters and check permissions.
When writing an application with a dynamic constructor type (late binding), you can replace it with the following method:
Class inheritance
Implemented through interfaces
Implemented through delegation

12. Avoid packing
Use the ToString method of value type to avoid packing
Cause: when the numbers and strings are spliced, the numbers can be spliced with strings only after being converted to the reference type through the boxing operation because of different data types.
// Suggestions
Int num = 5;
String str = "link me" + num. ToString ();


13. HttpServerUtility. Transfer
Use the Server. Transfer syntax to avoid unnecessary client redirection (Response. Redirect) by using this method on the page ).

Int32.TryParse ()
Type conversion Int32.TryParse () is better than Int32.Parse () than Convert. ToInt32 ()

Convert. ToInt32 will delegate the final parsing work to Int32.Parse

Int32.Parse will delegate the final parsing work to Number. ParseInt32

Int32.TryParse will delegate the final parsing work to Number. TryParseInt32

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.