StringBuilder vs. String / Fast String Operations with .NET 2.0
Conclusions
The following recommendations are valid for our small test strings (~30 chars) but should be applicable to bigger strings (100-500) as well (measure for yourself!). I have seen many synthetic performance measurements that demonstrate the power of StringBuilder with strings that are 10KB and bigger. This is the 1% case in real world programs. Most strings will be significantly shorter. When you optimize a function and you can "feel" the construction costs of an additional object then you have to look very carefully if you can afford the additional initialization costs of StringBuilder.
| String Operation | Most Efficient |
| Insert | StringBuilder.Insert > 2 Insertion Strings String.Insert otherwise |
| Remove | StringBuilder is faster > 2 characters to remove |
| Replace | String.Replace always |
| Format | String.Format < 5 Append + Format operations StringBuilder.AppendFormat > 5 calls |
| Concatenation | + for 2 strings String.Join > 2 strings to concatenate |
The shiny performance saving StringBuilder does not help in all cases and is, in some cases, slower than other functions. When you want to have good string concatenation performance I recommend strongly that you use String .Join which does an incredible job.
本文通过一系列测试函数对比了.NET 2.0中不同字符串操作方法的性能,包括字符串插入、删除、替换等,并给出了实际应用中的推荐建议。
9万+

被折叠的 条评论
为什么被折叠?



