c# - StringBuilder 解决了什么问题?

标签 c# .net string stringbuilder string-building

我为什么要使用 StringBuilder简单地附加字符串?例如为什么要像这样实现:

StringBuilder sb = new StringBuilder;
sb.Append("A string");
sb.Append("Another string");

结束

String first = "A string";
first += "Another string";

?

最佳答案

StringBuilder 的文档解释其目的:

The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

关于c# - StringBuilder 解决了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5498868/

相关文章:

C#: 求PNG压缩算法/库

c# - InitializeLifetimeService 覆盖模式

c# - 在 MVVM 中使用一个 View 对多种类型进行 CRUD

c# - 如何比较数据表

C# 正则表达式匹配

c# - 使用 C# 将数据表动态转换为类对象

java - 如何将字符串转换为java列表?

python - pandas 数据框字符串格式(访问给定列)

python - 如何更改字典中的变量

c# - 将 Razor Web App 作为中间件插入 Web Api 元素时,不会加载 css