Kronon Kronon - 3 months ago 25
C# Question

String Concatenation Vs String Builder Append

So...I have this scenario where I have a Foreach loop that loops through a List of Checkboxes to check which are selected. For every selected checkbox, I have to do a pretty long string concatenation, involving 30 different strings of an average length of 20 characters, and then send it out as a HTTP request. 2 of the strings are dependant on the index/value of the checkbox selected.

The length of the List of Checkboxes is also variable depending upon the user's data. I would say the average length of the List would be 20, but it can go up to 50-60. So the worst case scenario would be performing the whole string concatenation 60 or so times.

For now I'm doing it with simple string concatenation via the '+' operator, but I'm wondering if it would be faster to do it with Stringbuilder. Of course, that means I'd have to either create a Stringbuilder object within the loop, or create it before the loop and call Stringbuilder.Remove at the end of it after sending out the HTTP request.

I appreciate any insights anybody can share regarding this issue.

EDIT

Thanks for all the replies everybody, so from what I've gathered, the best way for me to go about doing this would be something like:

StringBuilder sb = new StringBuilder();
foreach (CheckBox item in FriendCheckboxList)
{
if (item.Checked)
{
sb.Append(string1);
sb.Append(string2);
sb.Append(string3);
.
.
.
sb.Append(stringLast);

SendRequest(sb.ToString());
sb.Length = 0;
}
}

Answer

Use StringBuilder. That's what it's for.

Strings are immutable. String concatenation creates a new string, needing more memory, and is generally considered slow:

string a = "John" + " " + "Saunders";

This creates a string "John ", then creates another string "John Saunders", then finally, assigns that to "a". The "John " is left for garbage collection.

string a = "John";
a += " ";
a += "Saunders";

This is about the same, as "John" is replaced by a new string "John ", which is replaced by a new string "John Saunders". The originals are left to be garbage collected.

On the other hand, StringBuilder is designed to be appended, removed, etc.


Example:

StringBuilder sb = new StringBuilder();
for (int i=0; i<n; i++)
{
    sb.Length = 0;
    sb.Append(field1[i]);
    sb.Append(field2[i]);
    ...
    sb.Append(field30[i]);
    // Do something with sb.ToString();
}
Comments