Welcome to Bangladesh Microsoft Technology Community Sign in | Join | Help

Asp.Net Performance: Use explicit cast instead of using Eval

I have come through lots of examples in the web using DataBinder.Eval but if we go and see whats happening under the hood, we will find Eval uses reflection to evaluate argument passed.

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

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
=============
<ItemTemplate>
<div><%# ((DataRowView)Container.DataItem)["myfield"] %></div>
</ItemTemplate>

Option2 for DataReader
=====================
<ItemTemplate>
<div><%# ((DbDataRecord)Container.DataItem).GetString(0) %></div>
</ItemTemplate>

Option3 My favorite use of ItemDataBound Event
==================================================
protected void Repeater_ItemDataBound(Object sender, RepeaterItemEventArgs e)
{
  DataRowView data = (DataRowView)e.Item.DataItem;
  Response.Write(string.Format("<div>{0}</div>",data["myfield"]));
}

And if we are using Collection Objects as DataSource we can do something like this

List<Customer> 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("<div>{0}</div>",customer.FirstName));
}
Published Thursday, November 23, 2006 6:01 PM by Shahed

Comments

No Comments

Anonymous comments are disabled