C # Performance Tuning details
1. Use String. Empty to assign an initial value to a null string variable
String.Empty is a reference, and "" is the concrete realization
String Filter= "";//String filter=string not recommended. Empty; Suggestions
2, use Str. Length = = 0 Short string comparison
3, avoid unnecessary string toupper, ToLower class operation
Methods such as ToUpper and ToLower will regenerate string pairs
String.Compare can implement ignoring string case
Deprecated wording if (S1. ToUpper () ==s2. ToUpper ()) ...;//recommended notation if (String.Compare (S1, s2, true) = = 0) ...;
4, skillfully use the StringBuilder string splicing operation
5. Create StringBuilder should specify initial size
The default initial size is 16, and once you exceed it, you need to resize once and increase the GC pressure. It is recommended to specify an initial size based on experience values.
StringBuilder sb = new StringBuilder (); for (int i = 0; i <; i++) { sb. Append (i);} string s = sb. ToString ();//Recommended modification to StringBuilder SB = new StringBuilder, for (int i = 0; i <; i++) { sb. Append (i);} string s = sb. ToString ();
6. Avoid misuse of StringBuilder
string concatenation operations such as STR1+STR2+STR3+STR4 are compiled into String.Concat (STR1,STR2,STR3, STR4), but are more efficient than StringBuilder. String.Concat will determine the length of the string once, StringBuilder need to do resize, suitable for multiple generation of the string object case.
7, through the direct setting. Length=0 to initialize StringBuilder
Based on the experimental results, the same StringBuilder object is used more than once, by direct setting. Length=0 to initialize the fastest.
Stringbuiler sb = new StringBuilder (n); ... sb. Remove (0, sb.) Length); SB is not recommended. Length = 0; Suggestions
8, do not use. Length=0 to release StringBuilder-occupied memory
static void Test () { StringBuilder sb = new StringBuilder (n); for (int i = 0; i <; i++) { sb. Append (i); } String t = sb. ToString (); ...//other code snippets that do not use the variable SB . Length = 0; Remove the sentence manually emptying SB code, will release memory earlier}
9. To be Continued
This is the C # string operation-to reduce the content of garbage collection pressure, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!