This article summarizes common optimization principles for efficient C# coding, which is of great reference for C# programming. The specific list is as follows:
VS for statement
Foreach needs to have better execution efficiency than for
The average time spent on Foreach is only 30% of that of for. After the test results, we recommend using more efficient foreach
In addition, the time to write data in for is about 10 times that of reading data.
2. Avoid using ArrayList
The performance of ArrayList is low. Any object added to ArrayList must be enclosed. If the data is taken out from ArrayList, it must be unboxed back to the actual type.
The high performance of generic collections, generic collections are strongly typed
3. Use HashTable Dictionary Collection
When storing a small amount of data, it is recommended to use HashTable instead of dictionary collections such as StringDictionary, NameValueCollection, HybridCollection.
4. Declare constants for string containers
Declare constants for string containers, do not directly encapsulate strings in double quotes, to avoid string objects being continuously created and released in memory. Improve the access efficiency of string objects.
//avoidMyObject obj = new MyObject(); = “Active”; //recommendconst string c = “Acive”; MyObject obj = new MyObject(); = c;
5. Use() string comparison
Do not use UpperCase or LowerCase to convert the upper and lowercase strings, and then compare them.
Use() to ignore string case for comparison
String strTemp = “Active”; If((strTemp,”active”,true)==0){ (“Equal”); }
6. String String Strings with StringBuilder
①.String class objects are immutable (read-only). For the reassignment of String objects, the essence is to recreate a new String object and assign a new value to the object.
②. Maintain a string with a length equal to Capacity (can be regarded as a character array). When the string of Capacity's length is not enough to accommodate the result string, StringBuilder opens a new memory area with Capacity calculated by the above rules, copy the original string to the new memory area and then performs operations, and hand over the original string area to GC for recycling. Therefore, memory allocation and recycling are also involved. When using StringBuilder, it is best to estimate the required capacity, and use this capacity to initialize 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. If you want to ensure their thread-safety, you must manually implement the thread synchronization mechanism.
Read XML files
If you just read the data of XML objects, then replacing XMLDocument with read-only XPathDocument can improve performance
8. Avoid declaring variables in the circulation body. Variables should be declared outside the circulation body and initialized in the circulation body.
//avoidFor(int i=0;i<10;i++){ SomeClass obj = new SomeClass(); //… } //recommendSomeClass obj = null; For(int i=0; i<10; i++){ obj = new SomeClass(); //… }
9.Catch the specified exception
When catching exceptions, you should use specific exception classes to capture them, and define them in the order of the capture of the exception in the order from small to large.
Private void Find(object obj){ try{ (()); } catch(ArgumentNullException ane) { //… } catch(ArgumentException ae) { //… } catch(SystemException se) { //… } catch(Exception e) { //… } }
Do not use Exception control flow, it is well known to catch exceptions to lose performance. Therefore, it is best to avoid the occurrence of exceptions.
10. Use using and try/finally to clean up resources
The .NET platform provides GC (Garbage Collection) in memory management, which is responsible for automatically releasing managed resources and memory recycling, but it cannot release unmanaged resources. At this time, we must provide ourselves methods to free unmanaged resources allocated in the object.
Using unmanaged resources types must implement the Dispose method of the IDisposable interface to accurately release data
When using typed resources with Dispose method, the Dispose method should be called when it is finished to release unused resources in time.
Using using or try/finally can better ensure that the Dispose method is called in time
11. Avoid abuse of reflexes
Reflection is a relatively wasteful operation, and the abuse of reflection should be avoided.
Reasons affecting performance:
When using reflection to call types or trigger methods and access field properties, CLR needs to do more: check parameters, check permissions, etc.
When writing an application with a dynamic construct type (late binding), the following methods can be used to replace it
Inheritance relationship through class
Implemented through interface
Implemented by delegation
12. Avoid packing operations
Use the ToString method of value type to avoid boxing
Reason: When scribing numbers and strings, because the data types are different, the numbers can only be spliced with the string after being converted into reference types through boxing operations.
//suggestionint num=5; string str = “link me”+();
Using the syntax, using this method in the page avoids unnecessary client redirects().
()
Type conversion() is better than() is better than Convert.ToInt32()
Convert.ToInt32 will proxy the final parsing work to
Will proxy the final parsing work to Number.ParseInt32
Will proxy the final parsing work to Number.TryParseInt32
I believe that the C# optimization principle described in this article can play a certain reference role in everyone's C# programming design.