• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Container.DataItem is faster than Eval in ASP.NET

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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" >
 <ItemTemplate>
 <!-- Using Eval -->
 <%# Eval("Name") %>

 </ItemTemplate>
</asp:Repeater>

Or Container.DataItem:

<asp:Repeater runat="server" >
 <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".


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
JQueryAjax调用asp.net后台方法发布时间:2022-07-10
下一篇:
ASP.NET:UpdatePanel与Response.Write()不兼容解决方法发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap