开发者

string builder vs string [duplicate]

开发者 https://www.devze.com 2023-01-17 19:33 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: When to use StringBuilder?
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

When to use StringBuilder?

string is immutable and stringbuilder is mutable

开发者_开发问答

what is diffrent of string and string builder ? where do we use string builder ?


The main difference is that a StringBuilder is mutable (meaning that it can be modified), whereas a string is immutable (meaning that once it is constructed it cannot be modified).

This difference is important for example if you are trying to create a large string from lots of smaller strings. If you use a StringBuilder you append the strings without creating a new object, giving O(n) performance. If you use strings you create lots of intermediate strings which are immediately discarded, but all the extra copying means that it becomes an O(n2) operation.

Example code showing the usage of each for contructing a large string from many smaller strings:

String

string s = "";
for (int i = 0; i < 10000; ++i)
{
    s += "foo";
}

StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; ++i)
{
    sb.Append("foo");
}
string s = sb.ToString();


Aside from string being immutable and stringbuilder being mutable, you should use a string builder when you are going to be doing a lot of string concatenation, as that is a very expensive operation, especially when contained in a loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号