String Builders are said to be immutable ? What does that mean in C# .NET?

佐手、 提交于 2019-12-19 11:53:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!