Subscribe

Close

Thank you for visiting!

Please consider subscribing to the RSS feed or following me on Twitter.

Improve performance by using explicit cast instead of DataBinder.Eval

The DataBinder.Eval method is often used when you want to bind data to a control's template. What DataBinder.Eval really does is to cast Container.DataItem to its specific type, like this:

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

DataBinder.Eval uses .NET reflection in order to cast Container.DataItem to its specific type. The use of reflection in this method will give you a performance loss.

If performance is of importance in your application or if you know what type Container.DataItem is, it's better to use an explicit cast instead:

<%# ((DbDataRecord)Container.DataItem)["Heading"] %>

Comments

After a discussion at work today, and subsequent research, I can add that if you want to get optimal performance one should actually do <%# (Container.DataItem as DbDataRecord)["Heading"] %>.
The difference is pretty damn small though, and a cast would give better error messages, so one would really have to crave performance to use that :)

Good tip, Joel! Definitely one to know for the future.

To the top