c# - StringBuilder - 是否应该只使用 Append 和 AppendLine,而不在参数中组合字符串?

标签 c# string stringbuilder

我已经开始使用 StringBuilder,因为我听说它在输出字符串方面更加优化。

我的问题是关于 + 的使用,因为字符串是不可变的,当您将它们添加在一起时,它会分配一个新字符串。

如果我在 StringBuilder.Append 函数的参数中使用此运算符,我认为它基本上具有相同的开销。

例如:

string animal1 = "dog";
string animal2 = "cat";

stringBuilder.Append("Today I saw a " + animal1 + " and " + animal2);

我的猜测是,无论如何,这都可以将这些文本连接在一起分配内存。

我认为更有效(尽管很冗长)的方法是:

stringBuilder.Append("Today I saw a");
stringBuilder.Append(animal1);
stringBuilder.Append(" and ");
stringBuilder.Append(animal2);

这是正确的吗?

最佳答案

第二个示例中存在错误,因为您错过了“Today I saw a”和 animal1 之间的空格。除非您以过度的方式执行此操作(在具有多次迭代的循环内),否则您可能会发现没有可测量的差异,因此您最好的选择可能是以可读性为目标。

$"Today I saw a {animal1} and a {animal2}"

是的,我也在第二只动物之前添加了一个 a :) 但我不处理“an”的情况。

如果您希望所有这些附加内容不那么冗长,您还可以选择使用AppendFormat...

stringBuilder.AppendFormat("Today I saw a {0} and a {1}", animal1, animal2);

关于c# - StringBuilder - 是否应该只使用 Append 和 AppendLine,而不在参数中组合字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53958066/

相关文章:

c# - StringBuilder 与 StringWriter/StringReader

c# - 如何使用即兴接口(interface)访问代理对象

java - java 字符串生成器

c# - 以列表列表作为数据源的 RDLC 报告

string - 在 SWIFT 中遇到逗号时将字符串换行

c++ - C++ 如何使用 == 比较两个字符串?

java - 无法在 Java 中将 bigdecimal 转换为字符串

c# - StringBuilder 中的 system.outofmemoryexception

c# - AllowHtml 不适用于数组

c# - DataType(DataType.*) 的用途是什么?