Home > Article > Backend Development > C# string operations--reduce garbage collection pressure
C# Performance optimization details
1. Use string.Empty to assign an initial value to an empty string variable
String.Empty is a reference, and "" is the specific implementation
string filter=“”;//不建议 string filter=string.Empty; //建议
2. Use str.Length == 0 to compare empty strings
##The fastest method: if (str.Length == 0)
##3. Avoid unnecessary string ToUpper and ToLower operations
//不推荐的写法 if(s1.ToUpper()==s2.ToUpper()) …; //推荐的写法 if(String.Compare( s1, s2, true ) == 0) …;
[object Object]
StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.Append(i); } string s = sb.ToString(); //建议修改为 StringBuilder sb = new StringBuilder(256); for (int i = 0; i < 10; i++) { sb.Append(i); } string s = sb.ToString();
6. Avoid abusing StringBuilder
7. Initialize StringBuilder by directly setting .Length=0
StringBuiler sb = new StringBuilder(256); ...... sb.Remove(0, sb.Length); //不建议 sb.Length = 0; //建议
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(); ……//其他不使用变量sb的代码段 sb.Length = 0; //去掉该句手工清空sb代码,会更早释放内存 }
9. To be continued
The above is the content of C# string operation--reducing the pressure of garbage collection. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!