Thursday, January 10, 2008

Don't use Databinder.Eval, improve performance

Use explicit cast instead of using Eval


Eval uses reflection to evaluate argument passed.Reflection is the ability to read metadata at runtime

<%# DataBinder.Eval(Container.DataItem,"myfield") %>

But explicit casting can reduce the cost of reflection. Imagine if there is 30 rows and each row has 6 Eval calls. So there will be calls to Eval 180 times. And we should take this pretty seriously.So you must be thinking what to do. Hey we can simply do something like this and improve significant performance.


Option1=============

<%# ((DataRowView)Container.DataItem)["myfield"] %>

Option2 for DataReader=====================

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


Option3 use of ItemDataBound Event====================

protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e){ DataRowView data = (DataRowView)e.Item.DataItem; Response.Write(string.Format("

{0}
",data["myfield"]));}
And if we are using Collection Objects as DataSource we can do something like this List customers = GetCustomers();Repeater1.DataSource = customers;Repeater1.DataBind();....
protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e){ Customer customer = (Customer)e.Item.DataItem; Response.Write(string.Format("
{0}
",customer.FirstName));

No comments: