PDA

View Full Version : When exactly should a StringBuilder be used?


gicio
11-09-03, 03:37 PM
Hi!

I’m very interesting in when to use exactly the StringBuilder?

For example for something like this?:

String strTest1 = “This”;
String strTest2 = “Test”;
StringBuilder stbTest = new StringBuilder();
stbTest.Append(strTest1). Append(“is a ”). Append(stbTest);


can someone provide some sample codes when to use a StringBuilder?

And can someone tell me his experience about the performance of a StringBuilder?


Regards,


gicio

psoutham
11-22-03, 03:00 AM
Read this http://blogs.gotdotnet.com/ricom/PermaLink.aspx/6bf9bcbc-1da0-454e-b8ee-0a72e5c1548a

Hi!

I’m very interesting in when to use exactly the StringBuilder?

For example for something like this?:

String strTest1 = “This”;
String strTest2 = “Test”;
StringBuilder stbTest = new StringBuilder();
stbTest.Append(strTest1). Append(“is a ”). Append(stbTest);


can someone provide some sample codes when to use a StringBuilder?

And can someone tell me his experience about the performance of a StringBuilder?


Regards,


gicio

ben_
04-22-05, 02:49 PM
StringBuilders should be used when you want to create and manipulate a large string a lot.

Example:
StringBuilder.sb = new StringBuilder();
sb.Append("Pretend this is a really really really really long string");
sb.Insert(9, "that"); // adds 'that' to the string at char index 9
Response.Write(sb); // or Console.WriteLine(sb);

In terms of the performance difference, it can add up to quite a bit with arge strings. Each method in a regular string (like, Replace for instance) creates a new string in memory. Eg:
string z = "boo";
z = z.Replace("b", "m");
z = z.ToUpper();

This is actually 3 strings stored in the memory, compared to a StringBuilder,
StringBuilder z = new StringBuilder("boo");
z = z.Replace("b", "m");

This is 1 string in the memory.

It's not an issue with a smaller string like here, but if the string was for instance a thousand word block of text and you wanted to replace some words in it then it can add up to a fair amount of overhead.