I have an event handler that needs to determine a type and execute code if it matches a specific type. Originally we cast it to an object and if it wasn't null we executed the code, to speed it up I used reflection and it actually slowed it down and I don't understand why.
here is a code sample
Trace.Write("Starting using Reflection");
if (e.Item.GetType() == typeof(GridDataItem))
{
bool isWatch = Convert.ToBoolean(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
if (isWatch)
{
e.Item.Style["Font-Weight"] = "bold";
}
}
Trace.Write("Ending using Reflection");
Trace.Write("Starting using Cast");
GridDataItem gridItem = e.Item as GridDataItem;
if (gridItem !=null)
{
bool isWatch = Convert.ToBoolean(gridItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["IsWatch"]);
if (isWatch)
{
gridItem.Style["Font-Weight"] = "bold";
}
}
Trace.Write("Ending using Cast");
And this is the trace output I get
Starting using Reflection 0.79137944962406 0.576538
Ending using Reflection 0.791600842105263 0.000221
Starting using Cast 0.791623353383459 0.000023
Ending using Cast 0.791649308270677 0.000026
Starting using Reflection 0.876253801503759 0.084604
Ending using Reflection 0.87631790075188 0.000064
Starting using Cast 0.87633445112782 0.000017
Ending using Cast 0.87634950075188 0.000015
it's not a lot, but if we had to do this a lot over time it could add up.
It's common knowledge that reflection in . NET is slow, but why is that the case? This post aims to figure that out by looking at what reflection does under-the-hood.
Reflection is not THAT slow. Invoking a method by reflection is about 3 times slower than the normal way. That is no problem if you do this just once or in non-critical situations.
Reflection is slow because you are querying the assembly's metadata whereas casting simply changes the type of the object you are referencing.
The assembly's metadata is a useful store of information but that information is best used at compilation time rather than at execution time. That metadata is used by the compiler for static type checking (among other things). You are using that same metadata to look up type information at execution time (which is fine if you have no other choice) which is significantly slower than casting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With