How to make StringBuilder empty again in .NET 3.5 ?

Viewed 36952

I have a loop where i create some string value based on certain conditions. I did place StringBuilder object outside of the loop and each time i have new row in loop i need to clear StringBuilder appended values for this row.

How do i clear those?

        StringBuilder sb = new StringBuilder();

        foreach (DataRow row in recipientsList.Rows)
        {
            sb.Length = 0;
            sb.Append("<ul>");
            if (row["needsToActivate"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutActivationTemplate());
            }
            if (row["needsToEnterSite"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutEnteringWebsiteForTwoWeeksTemplate());
            }
            if (row["needsPicture"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutPicturesTemplate());
            }
            if (row["needsText"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutTextTemplate());
            }
            if (row["needsCharacteristic"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutCharateristicsTemplate());
            }
            if (row["needsHobby"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutHobbiesTemplate());
            }
            sb.Append("</ul>");
}

Code with accepted answer;

7 Answers

I faced similar issue.

This trick worked for me

sb.Replace(sb.ToString(), "");

This code will replace entire string with "".

What I learned is

sb.Length = 0;

But my answer includes a hint on how to use StringBuilder without fragmenting memory. You're being careful to set the length to zero and reuse it, so you're not reallocating it all the time. Why not go a step further, and reduce fragmentation or frequent allocations?

StringBuilder sb = new System.Text.StringBuilder(22_000); // preallocate ~20K

If you can pretty much tell how much space you should need, consider allocating the space the StringBuilder is going to use up-front. There is a reason why the constructor allows you to specify how much space to allocate -- it improves performance. One allocation all-at-once should be faster than lots of little allocations interspersed with others.

So, I'll run some data through the code, look at the StringBuilder size, multiply by some factor, and put that as an initial allocation size for the StringBuilder.

Related