Memory efficiency: passing HTML aspx page through codebehind
My goal is to generate the aspx code of the page as a string. I am calling the code below codebehind via asynchronous request in javascript and I am getting the response back via Response.Write
string html = string.Empty;
using (var memoryStream = new MemoryStream())
{
using (var streamWriter = new StreamWriter(memoryStream))
{
var htmlWriter = new HtmlTextWriter(streamWriter);
base.Render(htmlWriter);
htmlWriter.Flush();
memoryStream.Position = 0;
using (var streamReader = new StreamReader(memoryStream))
{
html = streamReader.ReadToEnd();
streamReader.Close();
}
}
}
Response.Write(html);
Response.End();
I want to ask what the above code is memory efficient, I think about "yield" to use as it evaluates lazily. I can assume that the memory efficiency is higher than the code.
+2
source to share
2 answers
Use StringWriter instead of MemoryStream, StreamWriter and StreamReader:
string html;
using (StringWriter stream = new StringWriter()) {
using (HtmlTextWriter writer = new HtmlTextWriter(stream)) {
base.Render(writer);
}
html = stream.ToString();
}
Response.Write(html);
Response.End();
The StringWriter has a built-in StringBuilder. The ToString method calls ToString on the Stringuilder, so it returns the internal string buffer as a string. This means the string is created only once and is not copied back and forth.
+2
source to share