开发者

How to make StringBuilder empty again in .NET 3.5 ?

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")开发者_如何学Go
            {
                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;


You can simply;

sb.Length = 0;


StringBuilder.Clear(); is what you want.


Set Length to 0, or in .Net 4 I believe you can call the new Clear() method.


Assuming you define your StringBuilder like this: StringBuilder sb = new StringBuilder();

You can do any of the following:

Call the Clear method:

for (int i = 0; i < 100; i++)
{
    sb.Clear();
    .. your code here ..
}

Set the length to zero:

for (int i = 0; i < 100; i++)
{
    sb.Length = 0;
    .. your code here ..
}

Set it to a new object:

for (int i = 0; i < 100; i++)
{
    sb = new StringBuilder();
    .. your code here ..
}


You can re-use a StringBuilder (with .Clear() or .Length = 0) but if you really want to optimize you should try to estimate the final length. If this grows a little each iteration, re-using could be slower (use more mem) than creating a new one each time.

foreach (DataRow row in recipientsList.Rows)
{
    int estimatedLength = 5000; // maybe a calculation based on row-data
    StringBuilder sb = new StringBuilder(estimatedLength);
    ....

}

So while the answers here about how to do it are correct, the best advice is not to do it . It is a micro-optimization, and you don't need the very small gains here and you don't want the (small) extra complications. You could optimize a little here if the resulting string is very large but certainly don't make this a habit.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜