One of the most powerful features in .NET is the ability to use reflection to do all kinds of neat stuff at runtime, like
- Find out what properties, fields, methods, etc. are in a class
- Create objects without knowing their type at compile time
- Call methods by name (even private ones)
- Check attributes on classes, methods, fields, …
- …
The web framework I built over the last few years, ProMesh.NET, relies on reflection for a lot of the features it offers. Often though, I am asked if the heave use of reflection doesn’t have a significant impact on performance.
My answer usually is: YES, but it doesn’t matter. Now you probably think that I don’t care about performance or that I’ve had too much too drink. None of the above. I’ll explain:
In ProMesh.NET, there’s a feature that allows you to just declare session properties in your class that will be constructed at runtime, like this:
private SessionProperty<string> _mySessionVar1;
or
private SessionProperty<string> _mySessionVar2 = new SessionProperty<string>();
You don’t have to initialize _mySessionVar1. The framework uses reflection to construct the object.
Creating _mySessionVar1 is about 20 times slower than creating _mySessionVar2. Shocking? Yes. Unacceptable? No!
The reason why it is not unacceptable is that it takes 2.2 µs (microseconds) to create _mySessionVar1, and 0.12 µs (microseconds) to create _mySessionVar2. These figures include dynamically iterating the over the class members, determining their type and looking up the appropriate constructor. This is the simplified code which creates the fields at runtime:
foreach (MemberInfo member in GetType().GetMembers()){ if (member is FieldInfo) { FieldInfo field = (FieldInfo) member;
ConstructorInfo constructor = field.FieldType.GetConstructor(Type.EmptyTypes);
field.SetValue(this, constructor.Invoke(new object[0])); }}
Considering this happens when a web page is requested, which usually involves some database access, a little disk access and some other time-consuming stuff, a complete web page request takes between 50ms and 2000ms. Assuming we have 20 session variables to construct at runtime, the overhead is … between 0.08% (worst case) and 0.002%.
So, yes it is MUCH slower, but it doesn’t matter. (not for applications of this kind)
This weblog is sponsored by The Vici Project.








