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 Answers
Know the answer? Post it. Somebody with the same question will find it here.
Mahesh ChandRank #1 · 393.4K reputationPosted Aug 20, 2010, 7:53 AM EDT
0
Yes this is correct. Every time you apply any operation on strings in .NET, they create a new allocation in memory. For example,
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.
0
Sam HobbsRank #108 · 20.5K reputationPosted Aug 20, 2010, 11:54 AM EDT
0
Another possibility would be to use string.Format.
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 ChandRank #1 · 393.4K reputationPosted Aug 20, 2010, 7:53 AM EDT
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.
Sam HobbsRank #108 · 20.5K reputationPosted Aug 20, 2010, 11:54 AM EDT
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 ChandRank #1 · 393.4K reputationPosted Aug 20, 2010, 5:37 PM EDT