问题
I was recently asked this question : What is the difference between String and StringBuilders ?
I knew I had read somewhere that StringBuilders are immutable, but what immutable was and how do operations on StringBuilder turn out to be faster than String, that I was unaware of.
Please can anyone help me understand this ?
回答1:
No, String
is immutable - whereas StringBuilder
is mutable. That's the whole point of it. You use it to build a string, usually from lots of append operations. You can do this without creating a fresh copy of all the data each time, which is what would happen if you use String
:
// Bad
string x = "";
for (int i = 0; i < 100; i++)
{
x += i;
}
// Good
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 100; i++)
{
builder.Append(i);
}
string x = builder.ToString();
See my article on string concatenation and my other article on strings in general for more details.
In general, an immutable data type is one where you can't change the data in an object after creation, whereas a mutable one lets you change (mutate, hence the name) it. It's not quite as simple as it sounds though - see Eric Lippert's blog post on kinds of immutability for more information.
回答2:
For string : every time a operation is performed on the string to change it ,it leads to a new instance.
For Further explanation please refer below link:
Difference between string and StringBuilder in c#
来源:https://stackoverflow.com/questions/11113774/string-builders-are-said-to-be-immutable-what-does-that-mean-in-c-sharp-net