Windows Phone Developers

Sunday, August 24, 2008

Avoiding Temporary Strings in C# / Reduce Unnecessary Garbage Collection in C#

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#

Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment