2009-11-10 60 views
5

在我最近使用Asp.net Mvc 2的項目中,我們發現DisplayFor存在性能問題。我不太確定這是真實問題還是我錯過了什麼?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)變得非常快。問題解決了,但我仍然想知道原因。 :)

謝謝,
梭萌

回答

0

的問題是,DisplayFor()使用,其被編譯並在運行時執行的lambda表達式。

因此,V1中的性能差異可以歸因於該「中間」編譯步驟。

V2只是一個不需要任何編譯的屬性訪問。

我在這裏猜測,但我想象IIS7足夠聰明,可以保存視圖(和編譯的lambda表達式)的緩存副本以供將來重用,這意味着後續渲染時間將與V1在IIS 6中。

+0

的假設IIS7是這裏的關鍵因素,是不正確的。請參閱Levi的答案以獲取正確的信息。 – thomasjo

+0

答案被接受後IIS7被提及,所以我不能刪除它:( – Codebrain