我已经构建了一个将 mvc 视图呈现为字符串并使用 HiQPDF 呈现 PDF 报告的应用程序。这很好用,但是,重复调用 IView.Render 会导致相当大的性能下降。每次调用都比前一次调用长约 1 秒 - 并且呈现的 html 几乎相同。
任何人都知道其他不会影响这种性能的 html 渲染方法吗?任何人都知道为什么我看到这段代码的性能如此糟糕?
protected string RenderViewToStringInternal(string viewPath, object model,
bool partial = false,
string master = null)
{
//Find cached view
ViewEngineResult viewEngineResult = _cachedViews.ContainsKey(viewPath) ? _cachedViews[viewPath] : null;
if (viewEngineResult == null)
{
//Get view engine result
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(Context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(Context, viewPath, master);
if (viewEngineResult != null)
{
_cachedViews.Add(viewPath, viewEngineResult);
}
}
if (viewEngineResult == null)
throw new FileNotFoundException("View not found");
// get the view and attach the model to view data
var view = viewEngineResult.View;
Context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(Context, view,
Context.Controller.ViewData,
Context.Controller.TempData,
sw);
DateTime start = DateTime.Now;
**view.Render(ctx, sw);** //This line's performance degrades after subsequent calls with similar data
DateTime end = DateTime.Now;
Logging.LogInformation(Logging.TraceType.UI, string.Format("ViewRenderer.RenderViewToStringInternal view.Render execution time: {0}", end.Subtract(start).TotalSeconds));
viewEngineResult.ViewEngine.ReleaseView(Context, view);
result = sw.ToString();
}
return result;
}