What is the difference between a mutable and immutable string in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
From http://yassershaikh.com/what-is-the-difference-between-strings-and-stringbuilder-in-c-net/
Short Answer : String is immutable – whereas StringBuilder is mutable.
What does that mean ? Wiki says : In object-oriented, an immutable object is an object whose state cannot be modified after it is created. This is in contrast to a mutable object, which can be modified after it is created.
From the StringBuilder Class documentation:
The String object is immutable. 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.
In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.
The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.
in implementation detail.
CLR2's System.String is mutable. StringBuilder.Append calling String.AppendInplace (private method)
CLR4's System.String is immutable. StringBuilder have Char array with chunking.
String
is immutablei.e. strings cannot be altered. When you alter a string (by adding to it for example), you are actually creating a new string.
But
StringBuilder
is not immutable (rather, it is mutable)so if you have to alter a string many times, such as multiple concatenations, then use
StringBuilder
.Immutable :
When you do some operation on a object, it creates a new object hence state is not modifiable as in case of string.
Mutable
When you perform some operation on a object, object itself modified no new obect created as in case of StringBuilder
In .NET System.String (aka string) is a immutable object. That means when you create an object you can not change it's value afterwards. You can only recreate a immutable object.
System.Text.StringBuilder is mutable equivalent of System.String and you can chane its value
For Example:
Generates following MSIL : If you investigate the code. You will see that whenever you chane an object of System.String you are actually creating new one. But in System.Text.StringBuilder whenever you change the value of text you dont recreate the object.