内存效率:通过codebehind传递aspx页面的Html代码
我的目标是以字符串的形式生成页面的aspx代码。我通过javascript中的异步请求调用下面的代码隐藏代码,并且我通过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();
我想问的是上面的代码是内存效率,我正在考虑使用“yield”,因为它会延迟评估。您可以对上述代码的内存效率提出建议吗?
My goal is to generate the aspx code of a page in the form of string.I am calling the below codebehind code through asynchronous request in javascript and i am getting the response back through 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 that is the above code is memory efficient, I am thinking of "yield" to use as it evaluates lazily.Can u suggest on memory efficency of above code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 StringWriter 代替 MemoryStream、StreamWriter 和 StreamReader:
StringWriter 内部使用 StringBuilder。 ToString 方法调用 Stringuilder 上的 ToString,因此它返回内部字符串缓冲区作为字符串。这意味着该字符串仅创建一次,并且不会来回复制。
Use a StringWriter instead of the MemoryStream, the StreamWriter and the StreamReader:
The StringWriter uses a StringBuilder internally. The ToString method calls ToString on the Stringuilder, so it returns the internal string buffer as the string. That means that the string is only created once, and not copied back and forth.
您的方法将一个 html 副本存储在
html
变量中,并将另一个副本存储在memoryStream
中。试试这个:虽然这可行,但我不确定你想实现什么目标。
Your method stores an html copy at
html
variable, and another atmemoryStream
. Try this:While this can work, I'm not sure what are you trying to accomplish.