String builder question

S

simonZ

I read some articles about stringBuilder vs string.

I'm using the loop, so I must use string builder.
My example:

String s1;
String s2;
String s3;
StringBuilder webLines=new StringBuilder(10000);

for (int i = 0; i < 10000; i++)
{
s1="get from logic 1"
s2="get from logic 2"
s3="get from logic 3"

webLines.Append("<tr><tD nowrap>");
webLines.Append(s1);
webLines.Append("</td><td nowrap>");
webLines.Append(formatR(s2, 2));
webLines.Append("</tD><td nowrap>");
webLines.Append(s3);
webLines.Append("</td></tr>");

//this is better performance than using:
//webLine.Append("<tr><tD nowrap>" + s1 + "</td><td nowrap>" +
//formatR(s2,2) + "</tD><td nowrap>" + s3 + "</td></tr>");

}

If I use append for each word (my real example has much more words than this
one)
than I must write a lot of lines of code.
Could I somehowe append all words in one line with the same performance?

Something like:

webLines.Append(String.Concat("<tr><tD nowrap>" + s1 + "</td><td nowrap>" +
formatR(s2,2) + "</tD><td nowrap>" + s3 + "</td></tr>"));

What do you think?

Regards,Simon
 
T

Truong Hong Thi

I guess you meant commas, not plus operators, when passing arguments to
String.Concat.

However, String.Concat is just the same as + operator in that case, and
only one temp string is created for that. Because you call it in the
loop, 10000 temp strings are created.

Why not create a helper method:
static void AppendToBuilder(StringBuilder builder, param string[]
strings)

Thi
http://thith.blogspot.com
 
H

Hans Kesting

webLine.Append( said:
formatR(s2,2) + "</tD><td nowrap>" + s3 + "</td></tr>");

This would create a temporary string before Appending it to the
StringBuilder. If you reaaly do it in one statement, the compiler will
translate this into one call of String.Concat (instead of multiple
separate concatenations).
webLines.Append("<tr><tD nowrap>");
webLines.Append(s1);
webLines.Append("</td><td nowrap>");
webLines.Append(formatR(s2, 2));
webLines.Append("</tD><td nowrap>");
webLines.Append(s3);
webLines.Append("</td></tr>");

You could also write this as
webLines.Append("<tr><tD nowrap>").Append(s1).Append("</td><td
nowrap>") (and so on)


Hans Kesting
 
M

mostly_magic

I'm not sure about what happens with this in regards to temporary
strings, but you could also use AppendFormat:

webLines.AppendFormat(@"<tr><tD nowrap>{0}
</td><td nowrap>{1}
</tD><td nowrap>{2}</td></tr>",
s1, formatR(s2, 2), s3);

Cheers,
Mitchell Cowie
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top