views:

90

answers:

1

I am outputting the entire HTML for my server control as follows:

public override void Render(HtmlTextWriter output)
{
  output.Write(myStringBuilder.ToString());
}

myStringBuilder is a StringBuilder object that is manually built in a separate private method.

Is this an efficient way to do it? Or is it better to pass the HtmlTextWriter to my private method and make multiple calls to HtmlTextWriter.Write()?

+5  A: 

It's more efficient to pass the HtmlTextWriter down to your method, then it's writing to the output stream, not buffering up multiple strings.

In fact, this is the way the webcontrols in the core .Net framework are. At a high level, it's a lot of passing the same HtmlTextWriter down into all the Render methods. Usually, when doing a lot of reading/writing, dealing with a stream is more efficient...which is ultimately what you're doing (the stream being the Reponse stream in this case).

Disclaimer: This is a small optimization unless you're creating something monolithic...but an optimization none the less.

Nick Craver
And for the love of code, don't think that throwing a stringbuilder in the mix will help things. :)
Jason Hernandez