String is immutable
We heard that many times but most of us don't know what that means.
We heard that many times but most of us don't know what that means.
Here is the explanation for what is mutable
and what is immutable..
Mutable and immutable are merely just English words as the meaning of these words
In .Net C# , we have 'string' object and 'StringBuilder' object
String
String is immutable . That means a if we define a string it will create a sting object ,if we change the value of our sting then also create another sting object. If we try to concatenate it will also create another string object.
- 'Can change' - Mutable
- 'Cannot change'- Immutable
In .Net C# , we have 'string' object and 'StringBuilder' object
String
String is immutable . That means a if we define a string it will create a sting object ,if we change the value of our sting then also create another sting object. If we try to concatenate it will also create another string object.
string
immutableStr = string.Empty;
for
(int
i = 0; i < 100; i++)
{
immutableStr
= immutableStr + i.ToString();
}
In the above example , we the variable 'immutablestr' will be assigned 100 times. Each time new object is assigned for the same variable.
StringBuilder
StringBuilder is mutable string type. when stringbuilder is invoked, then allocate a memory for it and what happening is , append the new string to it. There wont be any extra memory allocation for StringBuilder.
In above there wont be any new memory allocation inside for loop only appending data to the previous 'mutablestr' variable.
StringBuilder
StringBuilder is mutable string type. when stringbuilder is invoked, then allocate a memory for it and what happening is , append the new string to it. There wont be any extra memory allocation for StringBuilder.
System.Text.StringBuilder mutableStr =
new System.Text.StringBuilder();
for
(int
i = 0; i < 100; i++)
{
mutableStr
= mutableStr.Append(i);
}In above there wont be any new memory allocation inside for loop only appending data to the previous 'mutablestr' variable.
No comments:
Post a Comment