C # string operation-reduce the garbage collection pressure
1. Use string. Empty to assign an initial value to an Empty string variable.
String. Empty is a reference, and "" is a specific implementation.
String filter = ""; // string filter = string. Empty is not recommended; // recommended
2. Use str. Length = 0 for empty string comparison
The fastest way: if (str. Length = 0)
Second: if (str = String. Empty) or if (str =)
3. Avoid unnecessary string ToUpper and ToLower operations
Methods such as ToUpper and ToLower will regenerate string pairs.
String. Compare can ignore String case sensitivity
// The statement is not recommended. if (s1.ToUpper () = s2.ToUpper ())...; // Recommended statement: if (String. Compare (s1, s2, true) = 0 )...;
4. Use StringBuilder to concatenate strings
If you want to construct a long string, especially when splicing for more than 10 times (experience value), use StringBuilder for String concatenation.
// Not recommended: string s = null; for (int I = 0; I <10000; I ++) {s + = I ;}// recommended: stringBuilder sb = new StringBuilder (); for (int I = 0; I <10000; I ++) {sb. append (I);} string t = sb. toString ();
5. Specify the initial size when creating StringBuilder.
The default initial size is 16. Once the size exceeds 16, it needs to be Resize once and increase the GC pressure. We recommend that you specify the initial size based on the experience value.
StringBuilder sb = new StringBuilder (); for (int I = 0; I <10; I ++) {sb. append (I);} string s = sb. toString (); // we recommend that you change it to StringBuilder sb = new StringBuilder (256); for (int I = 0; I <10; I ++) {sb. append (I);} string s = sb. toString ();
6. avoid abuse of StringBuilder
String concatenation operations similar to str1 + str2 + str3 + str4 are compiled into String. Concat (str1, str2, str3, str4), which is more efficient than StringBuilder. String. Concat determines the length of the string at a time. The Resize function of StringBuilder is suitable for generating String objects multiple times.
7. initialize StringBuilder by directly setting. Length = 0.
Based on the experiment results, when you use the same StringBuilder object multiple times, you can set. Length = 0 to initialize the object as quickly as possible.
StringBuiler sb = new StringBuilder (256); ...... sb. Remove (0, sb. Length); // do not recommend sb. Length = 0; // recommended
8. Do not use. Length = 0 to release the memory occupied by StringBuilder.
Static void test () {StringBuilder sb = new StringBuilder (256); for (int I = 0; I <100; I ++) {sb. append (I);} string t = sb. toString ();...... // Other code segments that do not use the variable sb. Length = 0; // remove this sentence to manually clear the sb code and release the memory earlier}