Coding with passion

首页 新随笔 联系 订阅 管理

In ASP.NET, the databinding expression <%# some expression %> is evaludated during the data binding phase. You can use two ways to write the evaluation expressions. However, it's recommended that we use "Container.DataItem" for performance reason. For example, the data source is a collection of strongly-typed objects, "Employee" objects.

public class Employee
{
 private string _name;
 
 public string Name
 {
 get{ return _name; }
 set{ _name = value; }
 }
}

Eval:

<asp:Repeater runat="server" id="MyRepeater1">
 <ItemTemplate>
 <!-- Using Eval -->
 <%# Eval("Name") %>

 </ItemTemplate>
</asp:Repeater>

Or Container.DataItem:

<asp:Repeater runat="server" id="MyRepeater2">
 <ItemTemplate>

 <!-- Using Container.DataItem -->
 <%# ((Employee)Container.DataItem).Name %>
 </ItemTemplate>
</asp:Repeater>

As we known, the code above will be finally compiled into an assembly. The assembly will be stored a directory under "Temporary ASP.NET Files". Its name and directory name are both randomly generated by ASP.NET system. For example: C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\webapp name\050f3065\32a6c804\App_Web_xcctyfc6.dll. The full path can be determined by the C# statement:

System.Web.Compilation.BuildManager.GetCompiledAssembly( Request.FilePath ).Location

Let's take a look at the code with the help of a free tool called Reflector. Then we'll know how the piece of code will run on web servers.

Eval:

DataBoundLiteralControl control = (DataBoundLiteralControl) sender;
RepeaterItem bindingContainer = (RepeaterItem) control.BindingContainer;
control.SetDataBoundString(0, Convert.ToString(base.Eval("Value"), CultureInfo.CurrentCulture));

Eval was defined in System.Web.UI.TemplateControl, and it will finally call System.Web.UI.DataBinder.Eval method.

Container.DataItem:

DataBoundLiteralControl control = (DataBoundLiteralControl) sender;
RepeaterItem bindingContainer = (RepeaterItem) control.BindingContainer;
control.SetDataBoundString(0, Convert.ToString(((Employee) bindingContainer.DataItem).Value, CultureInfo.CurrentCulture));

"Eval" evaludates the specified expression using reflection technology. "Container.DataItem" just need a simple casting operation. The latter one will obviously cost less resouces, and as a result have a better performance. This is also proven by my own tests. I found that "Container.DataItem" is always 7 to 10 times faster than "Eval".

posted on 2007-08-28 00:04  Kellin  阅读(2071)  评论(7编辑  收藏  举报