I’ve come across this one several times when working with ASP.NET. When you want to put something from .NET onto your ASP.NET page, it is common to do one of these:
<%# Eval(“FirstName”) %>
<%# Bind(“FirstName”) %> //Bind is just a wrapper around Eval()
As opposed to something like this:
<%# ((DataRowView)Container.DataItem)["FirstName"] %>
<%# CType(Container.DataItem, System.Data.DataRowView)("FirstName") %>
The second one seems like more typing. Otherwise they seem pretty close. So, a lot of developers figure: go with fewer words. It’s the kiss principle (keep it simply simple). Guess what? This simple way is a performance killer.
Eval() command uses reflection to evaluate this expression. In case you are not familiar with reflection, it is bad. It is a notorious performance hog and you should avoid it whenever possible. Microsoft even warns you in the MSDN article about
Eval (http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx#remarksToggle read the section under “Note”).
Think of it like this:
Eval takes about 1/20th of a second per call, and the other way takes about 1/1000th of a second per call. On a grid with 5 columns and 8 rows, Eval would take 2 seconds and the other would take under 1 second. Nobody would notice the difference. However, change that grid to 10 columns and 50 rows. You now have a difference of 25 seconds. It is the kind of thing that might not matter very much, most of the time but when it does, it makes a big difference.
Once, I had a discussion with a seasoned developer about this topic and he asked “If
Eval() is so bad, why would Microsoft leave it in there and refer to it in so many of their docs and online examples?” The reason is: these docs are for newbies and rookies. People who are just starting-out seem to prefer the simplest ways of doing things.
Do you think you should give a rookie the task of building a demanding web page that needs to scale really well or requires peak performance? Someday, yes, but at first, the rookie just wants to get his stuff to run. He needs to crawl before he walks/runs. Knowing how to tune your apps to perform-well is a craft and it comes after experience. Some consider it a bit of a right-of-passage. The day you turn from your
Eval() ways, is the day you become a man in the .NET world. In contrast, if you are still using
Eval, then it is time for you to move out of your mom’s basement and start using strong-types. You don’t need reflection to do your heavy-lifting any more. You know what Type that databinder is using. So get it together and type-cast it like a senior developer and stop wasting all of those CPU ticks.
If you would like to read more, let me recommend the following articles:
So always remember: "
Eval is evil". If you have any dignity at all, as a programmer, you are now compelled to banish it forever. If you ever see it in any code, anywhere, light a torch or grab a pitchfork and run it out of town like the monster that it is.