Strings of type System.String are immutable (read-only) in .NET because its value cannot be modified once it has been created. That means any change to a string causes the runtime to create a new string object and abandon the old one. That happens invisibly. Following code allocates three new strings in memory:
string str = "This is Programming360 Blog. ";
str += "It educate technical communities. ";
str += "It believes, one concept at a time...";
Only the last string has a reference; the other two will be disposed of during garbage collection. Avoiding these types of temporary strings helps avoid unnecessary garbage collection, which improves performance. There are several ways to avoid temporary strings:
* Use the String class's Concat, Join, or Format methods to join multiple items in a single statement.
* Use the StringBuilder class to create dynamic (mutable) strings.
The StringBuilder solution is the most flexible because it can span multiple statements. The default constructor creates a buffer 16 bytes long, which grows as needed. You can specify an initial size and a maximum size if you like.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("This is Programming360 Blog. ");
sb.Appen("It educate technical communities. ";);
sb.Appen("It believes, one concept at at time...");