Thursday, July 3, 2008

StringBuilder and String Concatenation

StringBuilder and String Concatenation: "StringBuilder and String Concatenation"

// Put user code to initialize the page here
// Concatenation using string
Console.WriteLine("String routine");
string str = string.Empty;
DateTime startTime = DateTime.Now;
Console.WriteLine("Start time:" + startTime.ToString());
for(int i=0; i<10; i++)
{
str += i.ToString();
}
DateTime stopTime = DateTime.Now;
Console.WriteLine("Stop time:" + stopTime.ToString());

Listing 1

Now let's see the routine that uses the StringBuidler class. As you can see from Listing 2, we do the exact sample operation but this time we use StringBuilder.Append method to concatenate strings.

// Concatenation using StringBuilder
Console.WriteLine("StringBuilder routine");
StringBuilder builder = new StringBuilder();
startTime = DateTime.Now;
Console.WriteLine("Start time:" + startTime.ToString());
for(int i=0; i<10; i++)
{
builder.Append(i.ToString());
}
stopTime = DateTime.Now;
Console.WriteLine("Stop time:" + stopTime.ToString());

www.visli.com

No comments: