RSS

StringBuilder append Vs String Concatenation “+”

10 Sep

For all of you looking for proof that Stringbuilder is faster than the normal string concatenation using “+”

In the following code snippet i have used both the methods and used start time and end time in each method to calculate the Elasped time for each respective method Create a new project and add the necessary labels and the button to check it for yourself.

private void Calculatebutton_Click(object sender, System.EventArgs e)

{

DateTime plusStart;

DateTime plusEnd;

DateTime bldrStart;

DateTime bldrEnd;

string test = String.Empty;

string stringToAppend = “ap”;

System.Text.StringBuilder sb = new System.Text.StringBuilder();

int upperlimit = 100000;

plusStart = DateTime.Now;

for (int i=0 ; i < upperlimit ; i ++ )

{

test += stringToAppend;

}

plusEnd = DateTime.Now;

plusElaspedlabel.Text = plusEnd.Subtract(plusStart).ToString();

plusEndlabel.Text = plusEnd.ToString();

plusStartlabel.Text = plusStart.ToString();

bldrStart = DateTime.Now;

for (int j=0; j < upperlimit ; j ++ )

{

sb.Append(stringToAppend);

}

bldrEnd = DateTime.Now;

bldrElaspedlabel.Text = bldrEnd.Subtract(bldrStart).ToString();

bldrEndlabel.Text = bldrEnd.ToString();

bldrStartlabel.Text = bldrStart.ToString();

}

Advertisements
 
Leave a comment

Posted by on September 10, 2008 in .NET, Bouncing Wall!!, Code Snippets

 

Tags: , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: