| .NET reflection - performance |
|
Welcome to this attempt to have an outlet for thoughts, programming quirks and other oddities which might be of general interest. In course of the work for Spielwerke, I had to investigate .NET performance for access to properties via reflection. The .NET framework offers two ways for this: direct reflection (System.Reflection) and "reflection" via System.ComponentModel.TypeDescriptor - surprisingly, the latter can turn out to be faster than the former, especially if your types implement System.ComponentModel.ICustomTypeDescriptor. If you have looked into .NET performance pitfalls before, it might not surprise you how slow the normal reflection is: a simple test with repeated access to an int property proved to be ~1000 times slower using reflection compared to the direct access to the property (comparing the average of the median 80% of the measured times). Fortunately there are some ways to do the dynamic access a lot faster: starting from the examples in this article from James Nies - which also has some measurements regarding performance - and this one from Tobias Hertkorn, it is possible to get a property accessor together which uses for creation and access only the object reference and the name of the property in the object, and uses only .NET 2.0 standard C# (no emitting of MSIL code) and runs less than 10 times slower than the direct access - still a magnitude difference, but at least two magnitudes faster than using reflection as it normally works. I hope I will find the time to elaborate on that soon. Lesson learned: try to avoid dynamic calls - everything which uses Invoke with generic object parameters will be very slow. Second lesson (re-)learned: reflectors can be a very, very useful tool to find out what .NET does internally. Achim Comments
(0)
|