5

在我最近使用 Asp.net Mvc 2 的项目中,我们发现 DisplayFor 存在性能问题。我不太确定这是真正的问题还是我错过了什么?

我希望一些 Asp.net Mvc Guru 可以向我解释。:)

模型。

public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string EmailAddress { get; set; }

    public static IEnumerable<Customer> GetCustomers()
    {            
        for (int i = 0; i < 1000; i++)
        {
            var cust = new Customer()
            {
                CustomerId = i + 1,
                Name = "Name - " + (i + 1),
                Address = "Somewhere in the Earth...",
                EmailAddress = "customerABC"
            };

            yield return cust;
        }
    }
}

控制器

public ActionResult V1()
    {            
        return View(Customer.GetCustomers());
    }

    public ActionResult V2()
    {
        return View(Customer.GetCustomers());
    }

V1(有性能问题)

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Customer>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    V1
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>V1</h2>
    <table>
    <%foreach (var cust in this.Model)
      {%>
        <%= Html.DisplayFor(m => cust) %>  
      <%} %>
    </table>
</asp:Content>

模板是

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Customer>" %>
<tr>
    <td><%= this.Model.CustomerId %></td>
    <td><%= this.Model.Name %></td>
    <td><%= this.Model.Address %></td>
    <td><%= this.Model.EmailAddress %></td>    
</tr>

V2(无性能问题)

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Customer>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    V2
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2>V2</h2>
    <table>
    <%foreach (var cust in this.Model)
      {%>
        <tr>
            <td><%= cust.CustomerId%></td>
            <td><%= cust.Name%></td>
            <td><%= cust.Address%></td>
            <td><%= cust.EmailAddress%></td>    
        </tr>
      <%} %>
      </table>
</asp:Content>

我可以很容易地看到 V1 和 V2 之间的性能差异。

编辑:当我部署到我的本地 IIS 7(带有发布版本)并且它(V1)变得非常快。问题解决了,但还是想知道原因。:)

谢谢,
苏萌

4

2 回答 2

12

缓存仅在发布模式下启用。如果您在调试模式下运行应用程序,您可能会看到由于磁盘访问而导致的性能下降。

另见: http ://codeclimber.net.nz/archive/2009/04/22/how-to-improve-htmlhelper.renderpartial-performances-donrsquot-run-in-debug-mode.aspx

于 2009-11-11T19:40:18.167 回答
0

问题是 DisplayFor() 使用在运行时编译和执行的 lambda 表达式。

因此,V1 中的性能差异可以归因于这个“中间”编译步骤。

V2 只是一个不需要任何编译的属性访问。

我在这里猜测,但我认为 IIS7 足够聪明,可以保留视图的缓存副本(和编译的 lambda 表达式)以供将来重用,这意味着后续渲染时间将与 IIS 6 中的 V1 相当.

于 2009-11-10T16:16:26.397 回答