Hi, this may seem like a trivial question but I want to get a full understanding of when to use this.
I am writing C sharp classes that contain methods which build up a big stream of HTML before passing it back as a String return value, which will then get put into an HTML page via a server control.
At the moment, the code is similar to
String htmlstring =
" +
"" +
"" +
"" +
"" +
"" +
"
" +
etc etc...
So I have massive big concatenation blocks, then maybe something like
while( reader.Read() )
{
InboxMessage message = InboxMessage.GetMessage( reader.GetInt64( "MessageId" ) );
htmlstring += "
Which loops through, concatenating each time. So I have both in-line concatenations being used heavily, and also cross-line using +=.
I want to know the best way to do this, should I leave it as is or will I benefit from using the Stringbuilder class. I am not sure if the String concat overhead just occurs with the += concats, or with all the in-line ones too. ie Does String s = "test" + "hello" + "now"; Create five objects in memory? One for test, one for hello, one for now, and then two for the two concats?
It seems a little heavyweight to use
StringBuilder htmlstring = new StringBuilder("
",5000);
htmlstring.Append("
");
htmlstring.Append( "
");
htmlstring.Append("");
htmlstring.Append("
");
htmlstring.Append("
");
htmlstring.Append("
");
htmlstring.Append("
");
htmlstring.Append("
" + _user.UserName + "
");
I'd appreciate anyones advice on this
3 Replies
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Mahesh ChandPosted Aug 20, 2010, 9:37 PM
Sam HobbsPosted Aug 20, 2010, 3:54 PM
Something I would do is to create a function to generate each element or set of elements or whatever is appropriate for the requirements.
Actually what I probably would do is to use the DOM to generate the HTML.
Mahesh ChandPosted Aug 20, 2010, 11:53 AM
string str = "mahesh";
str += "chand";
This actually not recycling str object. It would have two memory allocations.
Use StringBuilder and append strings to StringBuilder(). It will create one memory allocation for StringBuilder only.