Friday, August 5, 2011

Avoid DataBinder.Eval in ASP.NET and improve Performance


I see a lot of developers using DataBinder.Eval, which evaluates data-binding expressions at run time. Although the DataBinder.Eval is quite frequently used in web controls like the GridView, Repeater etc, use it with caution. Here’s what the documentation says

Because this method performs late-bound evaluation, using reflection at run time, it can cause performance to noticeably slow compared to standard ASP.NET data-binding syntax.
Let’s take an example to see how to avoid using DataBinder.Eval. Here’s some code that uses DataBinder.Eval() to display Person details







Although the markup looks tidy, for a large number of rows and columns, you are executing Eval() that many times, which will reduce performance since DataBinder.Eval() uses reflection to evaluate the data-binding expressions.
To avoid using DataBinder.Eval you can use the following alternatives:
For ObjectDataSource
If you are using an ObjectDataSource, refer directly to the Person class as shown below:
<asp:Repeater ID="rptPerson" runat="server">
    <ItemTemplate>
 <%# ((Person)Container.DataItem).FirstName %> 
<%# ((Person)Container.DataItem).LastName  %> 
<%# ((Person)Container.DataItem).Age  %>     
    </ItemTemplate>
</asp:Repeater>
For SqlDataSource
If you are using a SQLDataSource with a DataTable, use the following markup to cast the Container.DataItem as a DataRowView
<asp:Repeater ID="rptPerson" runat="server">
    <ItemTemplate>
        <%# ((DataRowView)Container.DataItem)["FirstName"] %> 
<%# ((DataRowView)Container.DataItem)["LastName"]%> 
<%# ((DataRowView)Container.DataItem)["Age"]%> 
</ItemTemplate>
</asp:Repeater>
Note: If you are using SqlDataSource with the DataReader mode, use DbDataRecord.

No comments:

Post a Comment