Appending strings to existing will produce garbage collection overhead for the program. Instead use Append method of StringBuilder class or Concat, Join methods of String class
The following code differentiates between both :
private void stringbuilder_example()
{
// Appending String - Garbage Collection - Immutable
string CompleteAddress = "";
CompleteAddress += "105, Annanagar ";
CompleteAddress += "Chennai ";
CompleteAddress += "Tamil Nadu ";
MessageBox.Show(CompleteAddress);
// Appending String - using String Builder
System.Text.StringBuilder CompleteAddress1 = new
System.Text.StringBuilder();
CompleteAddress1.Append( "105, Annanagar ");
CompleteAddress1.Append( "Chennai ");
CompleteAddress1.Append( "Tamil Nadu ");
// Error Code
//MessageBox.Show(CompleteAddress1);
// corrected Code
MessageBox.Show(CompleteAddress1.ToString() );
}
C# StringBuilder Class, C# StringBuilder Class Append Method, Appending Strings without Garbage Overhead, Avoiding Temporary Strings in C#, Reduce Unnecessary Garbage Collection in C#
No comments:
Post a Comment