ASP.NET 2.0 Performance Guidelines - Data Binding

From Guidance Share
Jump to navigationJump to search

- J.D. Meier, Srinath Vasireddy, Ashish Babbar, John Allen, and Alex Mackman


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.

DataBind();

The following line calls DataBind on the specific control.

yourServerControl.DataBind();



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.

<ItemTemplate>

<%# DataBinder.Eval(Container.DataItem,"field1") %> <%# DataBinder.Eval(Container.DataItem,"field2") %> </ItemTemplate> 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.

<ItemTemplate> <%# ((DataRowView)Container.DataItem)["field1"] %> <%# ((DataRowView)Container.DataItem)["field2"] %> </ItemTemplate> 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. <ItemTemplate> <%# ((DbDataRecord)Container.DataItem).GetString(0) %> <%# ((DbDataRecord)Container.DataItem).GetInt(1) %> </ItemTemplate> 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; Response.Write(string.Format("{0}",drv["field1"])); Response.Write(string.Format("{0}",drv["field2"])); Response.Write(string.Format("{0}",drv["field3"])); Response.Write(string.Format("{0}",drv["field4"]));

     }