简体   繁体   English

String 和 StringBuilder 的性能注意事项 - C#

[英]Performance considerations for String and StringBuilder - C#

All,全部,

For the string string s = "abcd" , does string w = s.SubString(2) return a new allocated String object ie string w = new String ("cd") internally or a String literal?对于字符串string s = "abcd"string w = s.SubString(2)返回一个新分配的 String object 即string w = new String ("cd")内部或字符串文字?

For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location or simply the pointers to each of the earlier String value are reassigned to the new location?对于 StringBuilder,当附加字符串值并且需要增加 StringBuilder 的大小时,是否将所有内容复制到新的 memory 位置,或者只是将指向每个较早字符串值的指针重新分配到新位置?

String is immutable, so any operation that "changes" the string, will in effect return a new string . String是不可变的,因此任何“更改”字符串的操作实际上都会返回一个new string This includes SubString and all other operations on String , including those that does not change the length (such as ToLower() or similar).这包括SubStringString上的所有其他操作,包括那些不改变长度的操作(例如 ToLower() 或类似的)。

StringBuilder contains internally a linked list of chunks of characters. StringBuilder内部包含一个字符块的链接列表。 When it needs to grow, a new chunk is allocated and inserted at the end of the list, and data is copied here.当它需要增长时,会分配一个新的块并插入到链表的末尾,并将数据复制到这里。 In other words, the whole StringBuilder buffer will not be copied on an append, only the data you are appending.换句话说,整个 StringBuilder 缓冲区不会被复制到 append 上,只会复制您要附加的数据。 I double-checked this against the Framework 4 reference sources.我根据 Framework 4 参考源对此进行了仔细检查。

For the string string s = "abcd", does string w = s.SubString(2) return a new allocated String object? Yes是的

For StringBuilder, when appending string values and if the size of the StringBuilder needs to be increased, are all the contents copied over to a new memory location? Yes是的

Any change in String small or large results in a new String String 的任何大小变化都会产生一个新的 String

Difference between the String and StringBuilder is an important concept which makes the difference when an application has to deal with the editing of a high number of Strings. StringStringBuilder之间的区别是一个重要的概念,当应用程序必须处理大量字符串的编辑时,它会有所不同。

String细绳

The String object is a collection of UTF-16 code units represented by a System.Char object which belong to the System namespace.字符串 object 是 UTF-16 代码单元的集合,由 System.Char object 表示,属于 System 命名空间。 Since the value of this objects are read-only, the entire object String has defined as immutable.由于此对象的值是只读的,因此整个 object 字符串已定义为不可变。 The maximum size of a String object in memory is 2 GB, or about 1 billion characters. memory 中的字符串 object 的最大大小为 2 GB,即大约 10 亿个字符。

Immutable Being immutable means that every time a methods of the System.String is used, a new sting object is created in memory and this cause a new allocation of space for the new object.不可变 不可变意味着每次使用 System.String 的方法时,都会在 memory 中创建一个新的字符串 object,这会为新的 ZA8CFDE6331BD59EB2AC96F8911C4B66 分配新的空间

Example: By using the string concatenation operator += appears that the value of the string variable named test change.示例:通过使用字符串连接运算符 += 出现名为 test 的字符串变量的值发生了变化。 In fact, it create a new String object, which has a different value and address from the original and assign it to the test variable.实际上,它创建了一个新的字符串 object,它与原来的值和地址不同,并将其分配给测试变量。

string test;
test += "red"; // a new object string is created
test += "coding"; // a new object string is created
test += "planet"; // a new object string is created

StringBuilder字符串生成器

The StringBuilder is a dynamic object which belong to the System.Text namespace and allow to modify the number of characters in the string that it encapsulates, this characteristic is called mutability. StringBuilder 是一个动态的 object,属于 System.Text 命名空间,允许修改它封装的字符串中的字符数,这个特性称为可变性。

Mutability To be able to append, remove, replace or insert characters, A StringBuilder maintains a buffer to accommodate expansions to the string.可变性为了能够 append、删除、替换或插入字符,StringBuilder 维护一个缓冲区以适应对字符串的扩展。 If new data is appended to the buffer if room is available;如果空间可用,则将新数据附加到缓冲区; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, and the new data is then appended to the new buffer.否则,分配一个新的、更大的缓冲区,将原始缓冲区中的数据复制到新缓冲区,然后将新数据附加到新缓冲区。

StringBuilder sb = new StringBuilder("");
sb.Append("red");
sb.Append("blue");
sb.Append("green ");
string colors = sb.ToString();

Performances表演

In order to help you better understand the performance difference between String and StringBuilder, I created the following example:为了帮助您更好地理解 String 和 StringBuilder 之间的性能差异,我创建了以下示例:

Stopwatch timer = new Stopwatch();
string str = string.Empty;
timer.Start();
for (int i = 0; i < 10000; i++) {
    str += i.ToString();
}
timer.Stop();
Console.WriteLine("String : {0}", timer.Elapsed);

timer.Restart();

StringBuilder sbr = new StringBuilder(string.Empty);
for (int i = 0; i < 10000; i++) {
    sbr.Append(i.ToString());
}
timer.Stop();
Console.WriteLine("StringBuilder : {0}", timer.Elapsed);

The output is output 是

Output
String : 00:00:00.0706661
StringBuilder : 00:00:00.0012373

Strings are immutable objects so every time you had to make changes you create a new instance of that string.字符串是不可变的对象,因此每次您必须进行更改时,您都会创建该字符串的新实例。 The substring method does not change the value of the original string. substring 方法不会改变原始字符串的值。

Regards.问候。

If you are going to make large numbers of edits to a string it better to do this via StringBuilder.如果您要对字符串进行大量编辑,最好通过 StringBuilder 执行此操作。

From MSDN :来自MSDN

You can use the StringBuilder class instead of the String class for operations that make multiple changes to the value of a string.您可以使用 StringBuilder class 而不是 String class 进行对字符串值进行多次更改的操作。 Unlike instances of the String class, StringBuilder objects are mutable;与 String class 的实例不同,StringBuilder 对象是可变的; when you concatenate, append, or delete substrings from a string, the operations are performed on a single string.当您连接 append 或从字符串中删除子字符串时,将对单个字符串执行操作。

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

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