简体   繁体   English

StringBuilder解决了什么问题?

[英]What problem does the StringBuilder solve?

Why would I use a StringBuilder over simply appending strings? 为什么我会使用StringBuilder而不是简单地附加字符串? For example why implement like: 例如为什么实现如下:

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

over 过度

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

?

The documentation of StringBuilder explains its purpose: StringBuilder的文档解释了它的用途:

The String object is immutable. String对象是不可变的。 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. 每次使用System.String类中的某个方法时,都会在内存中创建一个新的字符串对象,这需要为该新对象分配新的空间。 In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. 在需要对字符串执行重复修改的情况下,与创建新String对象相关的开销可能很昂贵。 The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. 如果要在不创建新对象的情况下修改字符串,可以使用System.Text.StringBuilder类。 For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop. 例如,使用StringBuilder类可以在循环中将多个字符串连接在一起时提高性能。

In a simple case like yours, it really doesn't matter. 在像你这样的简单案例中,它并不重要。 But generally, strings are immutable, that means every change to a string variable will create a new buffer in memory, copy the new data and abandon the old buffer. 但通常,字符串是不可变的,这意味着对字符串变量的每次更改都会在内存中创建一个新缓冲区,复制新数据并放弃旧缓冲区。 In case you are doing a lot of string manipulation, this slows down your program and leads to a lot of abandoned string buffers, that need to be collected by the garbage collector. 如果你正在进行大量的字符串操作,这会减慢你的程序并导致很多废弃的字符串缓冲区,需要由垃圾收集器收集。

Basically string immutability problems. 基本上是字符串不变性问题。 Also it provides methods for simpler manipulation of string. 它还提供了更简单的字符串操作方法。 Take a look at Using Stringbuilder Class 看看使用Stringbuilder类

StringBuilder is mutable. StringBuilder是可变的。 Strings are not. 字符串不是。 So any operation on a string creates a new object. 因此,对字符串的任何操作都会创建一个新对象。 In your 2nd sample, 2 objects are created (one on each line). 在第二个示例中,创建了两个对象(每行一个)。 Whereas in the first, only one object is created. 而在第一个中,只创建了一个对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM