Improving ASP.NET Performance Part 7: Data Binding

In our previous article in the ASP.NET performance series we discussed optimizing Server Controls. Let’s take a look at Data Binding, followed by Caching, but we’ll dedicate a separate article to that.

Data binding can often lead to performance problems if it is used inefficiently. If you use data binding, consider the following recommendations:

Avoid Using Page.DataBind

Calling Page.DataBind invokes the page-level method. The page-level method in turn calls the DataBind method of every control on the page that supports data binding. Instead of calling the page-level DataBind, call DataBind on specific controls. Both approaches are shown in the following examples.

The following line calls the page level DataBind. The page level DataBind in turn recursively calls DataBind on each control.



The following line calls DataBind on the specific control.


Minimize Calls to DataBinder.Eval

The DataBinder.Eval method uses reflection to evaluate the arguments that are passed in and to return the results. If you have a table that has 100 rows and 10 columns, you call DataBinder.Eval 1,000 times if you use DataBinder.Eval on each column. Your choice to use DataBinder.Eval is multiplied 1,000 times in this scenario. Limiting the use of DataBinder.Eval during data binding operations significantly improves page performance. Consider the following ItemTemplate element within a Repeater control using DataBinder.Eval.



    <td><%# DataBinder.Eval(Container.DataItem,”field1″) %></td>

    <td><%# DataBinder.Eval(Container.DataItem,”field2″) %></td>



There are alternatives to using DataBinder.Eval in this scenario. The alternatives include the following:

·         Use explicit casting. Using explicit casting offers better performance by avoiding the cost of reflection. Cast the Container.DataItem as a DataRowView.



    <td><%# ((DataRowView)Container.DataItem)[“field1”] %></td>

    <td><%# ((DataRowView)Container.DataItem)[“field2”] %></td>



You can gain even better performance with explicit casting if you use a DataReader to bind your control and use the specialized methods to retrieve your data. Cast the Container.DataItem as a DbDataRecord.



     <td><%# ((DbDataRecord)Container.DataItem).GetString(0) %></td>

     <td><%# ((DbDataRecord)Container.DataItem).GetInt(1) %></td>



The explicit casting depends on the type of data source you are binding to; the preceding code illustrates an example.

·         Use the ItemDataBound event. If the record that is being data bound contains many fields, it may be more efficient to use the ItemDataBound event. By using this event, you only perform the type conversion once. The following sample uses a DataSet object.

protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e)


  DataRowView drv = (DataRowView)e.Item.DataItem;







In our next article, we’ll discuss caching guidelines and best practices in detail.