Question about Literal performance

I am pretty new to the whole ASP atmosphere but at my new job this is what we use. There is quite a bit of code which looks like this:


MyLiteral.text = "This cool text" + variable1 + "more text" + variable2
MyLiteral.text &= "AnotherDiv" + variable3 + "more stuff"

You get the idea. To me, I would think it would be better performance wise to put this all in a stringbuilder, especially when it is something being run through many times. But I can’t find any information on the performance of the Literal.text method as opposed to a stringbuilder. Any thoughts?

To anwser the performance question, yes StringBuilder is FAR superior and performs much faster.

For Example.


Dim MyStringBuilder As New StringBuilder("Hello World!")
MyStringBuilder.Append(" What a beautiful day.")
Console.WriteLine(MyStringBuilder)

Welcome to .NET :slight_smile:

Thank you paperchaser :slight_smile: You will be seeing a lot of me! :slight_smile:

Really more of a memory pressure thing – .NET strings are immutable so you’ve just created a half dozen in your code. StringBuilder does some voodoo to avoid immutability.

In either case, you might be better served databinding within the aspx template rather than building strings in codebehind. Lot easier to tweak language . . .

wwb, thank you for the explanation. The reason this is built in the codebehind is that it is building product tables and such from the database.

So would the best performance in this situation be more like:


dim MyStringBuilder as New Stringbuilder("")
for each product
    MyStringBuilder.Append(" What a great product.")
    ....
next
MyLiteral.Text = MyStringBuilder.ToString()

or am I misunderstanding?

Thanks! Trying to learn best practices before I get too far into things.