This paper summarizes the common optimization principles of high-efficiency C # Coding, which is of great reference for C # programming. Specifically listed below:
1.foreach VS for statement
Foreach has better execution efficiency than for
The average time for foreach is only 30% for. With the test results available for both for and foreach, we recommend the use of more efficient foreach
In addition, the time to write data with for is about 10 times times the time of the read data.
2. Avoid using ArrayList
Poor performance of ArrayList any object that is added to the ArrayList is sealed to System.Object, and the data is removed from the ArrayList to be disassembled back to the actual type
The high performance of a generic collection class, a generic collection is a strongly-typed
3. Using the Hashtable dictionary collection
When storing small amounts of data, it is recommended to use Hashtable instead of a dictionary collection like Stringdictionary,namevaluecollection, Hybridcollection.
4. Declaring constants for a string container
Declare a constant for the string container, and do not enclose the string directly in the double quotation mark "" to prevent the string object from constantly being created and freed in memory. Improved access efficiency for string objects.
Avoid MyObject obj = new MyObject (); obj. Status = "Active";//Recommended Const string c = "Acive"; MyObject obj = new MyObject (); obj. Status = C;
5. Using the String.Compare () string comparison
Do not use uppercase or lowercase to convert the case of strings, and then compare
Compare using String.Compare () to ignore string case
String strtemp = "Active", If (String.Compare (strtemp, "active", true) ==0) { consolt.write ("Equal");}
6. Using StringBuilder string concatenation
The ①.string class object is immutable (read-only), and for a re-assignment of a string object, it is essential to recreate a new string object and give the new value to the object.
②.system.text.stringbuilder maintains a string of length equal to capacity (which can be treated as a character array), and when a string of capacity length is insufficient to accommodate the resulting string, StringBuilder opens a new length for the memory area of the capacity that has been calculated by the above rules, copies the original string to the new memory area and then operates, and the original string area is given to GC reclamation. So it also involves the allocation and recycling of memory, it is best to estimate the required capacity when using StringBuilder, and to initialize the capacity with this capacity to improve performance. StringBuilder cannot guarantee that all instance members are thread-safe, although many thread-safe controls are added to the type definition, and if you want to ensure that it is thread-safe, you must manually implement the thread synchronization mechanism.
7.XPathDocument Read XML file
If you just read the data from an XML object, you can improve performance by replacing XmlDocument with a read-only XPathDocument.
8. Avoid declaring variables in the loop body, declare variables outside the loop body, initialize variables in the loop body
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. Capturing the specified exception
When catching an exception, it should be captured with a specific exception class and defined in a small to large order according to the scope of the exception do not use the generic 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 the exception control process, and capturing the loss of performance is well known. So it's better to avoid the occurrence of an anomaly.
10. Use using and try/finally to clean up resources
The. NET platform provides GC (garbage Collection) in memory management, responsible for automating the release of managed resources and memory reclamation, but it cannot release unmanaged resources, at which point we must provide our own method to release the unmanaged resources allocated within the object
Types that use unmanaged resources must implement the Dispose method of the IDisposable interface to accurately release data
When you use a typed resource with the Dispose method, you should call the Dispose method when you are finished using it and release the unused resources in a timely manner.
Use using or try/finally to better ensure that the Dispose method is called in a timely manner
11. Avoid abuse of reflection
Reflection is a waste of performance, should avoid abuse of reflection
Reasons to affect performance:
When using reflection to invoke a type or trigger method, the CLR needs to do more to access the field properties: Validate parameters, check permissions, and so on.
When you write an app that dynamically constructs a type (late binding), you can replace it in the following ways
Inheriting relationships through classes
Implemented through interfaces
Implementation through delegation
12. Avoid Boxing operations
Use the ToString method of the value type to avoid boxing operations
Cause: When numbers and strings are stitched together, because of the different data types, numbers are converted to reference types by boxing operations before they can be spliced with strings.
suggested int num=5;string str = "link Me" +num. ToString ();
13.httpserverutility.transfer
Using the Server.Transfer syntax, use this method in the page to avoid unnecessary client redirection (Response.Redirect).
Int32.TryParse ()
Type conversion int32.tryparse () better than int32.parse () better 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.
It is believed that the C # optimization principle described in this paper can be used as a reference for the programming of C #.
In addition to the Declaration,
Running GuestArticles are original, reproduced please link to the form of the address of this article
Efficient C # Coding optimization Principles
This address: http://www.paobuke.com/develop/c-develop/pbk23671.html
Related content VS2013 Creating a graphics method for Windows services and debugging services C # Connecting a database Method C # Implementing a graphical area combination Operation C # implements the most complete example of file and directory operation classes
C # syntax is more unique than other languages (ii) C # simple alarm program using the Timer C # basic teaching IComparable usage, implementing List.sort () sorting string usages in C #
Efficient C # Coding optimization Principles