【问题标题】:Checking condition before/after RenderPartial performance在 RenderPartial 性能之前/之后检查条件
【发布时间】:2016-10-07 19:19:40
【问题描述】:

假设有一个RenderPartial 检查某个条件是否为真,然后呈现页面。

先检查条件,然后调用RenderPartial,是否有任何性能优势?我确信这种技术对RenderAction 的性能有好处,因为我们基本上可以通过 MVC 生命周期步骤进行短路。但我在想,既然RenderPartial“直接”进入视图,它可能不会有同样的好处。


示例(检查 RenderPartial 中的条件):


myPage.cshtml

@model Namespace.AdObject

@{ Html.RenderPartial("~/Views/Ad.cshtml", Model); }

~/Views/Ad.cshtml

@model Namespace.AdObject

@if (Model != null && Model.AdScript != null)
{
    // render the ad
}

示例(在 RenderPartial 之前检查条件):


myPage.cshtml

@model Namespace.AdObject

@if (Model != null && Model.AdScript != null)
{
    Html.RenderPartial("~/Views/Ad.cshtml", Model);
}

~/Views/Ad.cshtml

@model Namespace.AdObject

// render the ad

【问题讨论】:

  • 我相信你的做法是对的,直到条件为真才会调用渲染部分调用。

标签: c# asp.net asp.net-mvc asp.net-mvc-4 razor


【解决方案1】:

RenderPartial() 是一个写入响应输出流的 void 方法。 通过执行分部视图生成的 HTML 输出被渲染到调用(或父)视图中。即使模型是null,写入也会很耗时并且会降低效率。所以检查RenderPartial之前的条件在性能方面会更好。

【讨论】:

    【解决方案2】:

    我会说在 RenderPartial 调用之前检查更好。即使您的 Partial 视图很小,它仍然归结为从 Web 服务器对 .cshtml 文件的额外文件系统 IO 调用,这是性能的瓶颈。当您首先检查时,您可以一起避免 IO 调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多