我对使用 StringBuilder
类有点困惑,首先:
A
string
object concatenation operation always creates a new object from the existingstring
and the new data. AStringBuilder
object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
但是创建 StringBuilder
实例以避免创建新的 String
实例的意义何在?这听起来像是“一对一”交易。
static void Main(string[] args)
{
String foo = "123";
using (StringBuilder sb = new StringBuilder(foo)) // also sb isn't disposable, so there will be error
{
sb.Append("456");
foo = sb.ToString();
}
Console.WriteLine(foo);
Console.ReadKey();
}
为什么我不应该只使用
+=
编辑: 好的,我现在知道如何重用 StringBuilder
的一个实例(仍然不知道这是否适用于代码标准),但这不值得仅使用一个 string
,不是吗?
最佳答案
修改 immutable 结构如 string
s 必须通过复制结构来完成,这样会消耗更多内存并减慢应用程序的运行时间(还会增加 GC
时间等...)。
StringBuilder
通过使用相同的可变对象进行操作来解决这个问题。
但是:
在编译时连接 string
时如下:
string myString = "123";
myString += "234";
myString += "345";
它实际上会编译成这样的:
string myString = string.Concat("123", "234", "345");
这个函数比使用 StringBuilder
更快,因为输入函数的 string
数量是已知的。
所以对于编译时已知的 string
连接,您应该更喜欢 string.Concat()
。
对于未知数量的string
,如下情况:
string myString = "123";
if (Console.ReadLine() == "a")
{
myString += "234";
}
myString += "345";
现在编译器不能使用 string.Concat()
函数,但是,StringBuilder
似乎只有在串联时才更有效地消耗时间和内存使用 6-7 个或更多 strings
完成。
不良习惯用法:
StringBuilder myString = new StringBuilder("123");
myString.Append("234");
myString.Append("345");
精细练习用法(注意使用if
):
StringBuilder myString = new StringBuilder("123");
if (Console.ReadLine() == "a")
{
myString.Append("234");
}
myString.Append("345");
最佳实践用法(注意使用了while
循环):
StringBuilder myString = new StringBuilder("123");
while (Console.ReadLine() == "a")
{
myString.Append("234"); //Average loop times 4~ or more
}
myString.Append("345");
关于c# - 如何明智地使用 StringBuilder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21644658/