In my last post I mentioned the use of C style casting when databinding in ASP.NET. That got me thinking about the performance differences between the two main ways to bind data in controls with custom templates (GridView, DataList, Repeater, etc).
In my example I'm using a DataList and by default, Visual Studio will bind the data to your template controls using the "Eval" method.
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>'></asp:Label>
This method uses reflection and can be considerably slower depending on the complexity of your template and the number of properties you are binding. The attached code uses a very simple DataList with simple data. To see the difference in performance you'll need to increase the size of the data using the drop down list at the top.
Compare the performance using the "Eval" method to using the C style cast to access your object's properties.
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# ((Person)DataBinder.GetDataItem(Container)).FirstName %>'></asp:Label>
EDIT: As Bill pointed out in the comments, the call to DataBinder.GetDataItem() isn't necessary as you have access through the container already. I've updated the attached test code to include all three methods. These last two being equal in performance in my testing.
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# ((Person)Container.DataItem).FirstName %>'></asp:Label>
In my testing this method (the last two methods, actually) was (were) 3 - 4 times faster. As I said, this depends on the complexity of your control.
10-08-2007 10:14 AM