WHAT IS A STRINGBUILDER?PLEASE GIVE AN EXAMPLE?

Showing Answers 1 - 1 of 1 Answers

Nagendra Kumar K

  • Feb 21st, 2006
 

The String object is immutable. Every time you use one of the methods in the System.String class (appending string, remove string,....), it creates a new string object in memory, which requires a new allocation of space for the newly created (modified) string object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly.

// allocated memory in some location say 4253
string str = "India";  
// erases contents at 4253 and creates new memory location say 8578
str += " is my country";

Any modifications you do to the string object memory will change and it's very costlier.

The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.

So, to answer the question, at what point is it more efficient, I wrote a little tester. The StringBuilder returned Sub-10ms times (DateTime not capable of registering < 10ms) at 1000 or fewer iterations of a loop simply appending the string "string". The += method of concatenation takes 15+ms for the same iterations. At 5000 iterations, the += method was becoming much slower at 218ms. versus the StringBuilder which was still sub 10ms.Even at 10000 iterations, the SB was sub 10, while the concat method had gone over 1.2 seconds. My test code is as follows:

private void UpdateTime()

{

int iterations = Int32.Parse(txtIterations.Text);

string theString = txtTheString.Text;

DateTime strCall = DateTime.Now;

string targetString = null;

for(int x = 0 ; x < iterations ; x++)

{

targetString += theString;

}

TimeSpan time = (DateTime.Now - strCall);

txtConcatTime.Text = time.TotalMilliseconds.ToString();

//StringBuilder

DateTime inCall = DateTime.Now;

StringBuilder sb = new StringBuilder(theString);

for(int x = 0 ; x < iterations ; x++)

{

sb.Append(theString);

}

time = (DateTime.Now - inCall);

txtStringBTime.Text = time.TotalMilliseconds.ToString();

MessageBox.Show("done");

}

use StringBuilder whenever there is going to be a lot of modifications to the strings.

NOTE : The difference in performance when using with string object and StringBuilder can be check using .net profiler

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions