Thursday, June 18, 2009

Reflection

While trying to speed up an application I searched the internet for information about reflection. I use reflection quite often when I have to write a special XML serializer or when I have to write a simple OR mapper. The problem is that it is slow. I understand now also because you have to specify the type when you use the XmlSerializer of the .Net framework. Internally it generates IL code which speeds up the serialization a lot because the intermediate code is much faster than direct reflection.
Regarding this problem I found a very interesting blog post which you can check out here.
There a comparison is made between the direct reflection, reflection by using Reflection.Emit and by caching Reflection.Emit operations. As you can see there from the test results the cached reflection is about 8 times faster!! This may not be of importance if you serialize only 100 objects but if you serialize thousands or millions of objects than this makes a big difference.
I tried his code in a project of mine where I use quite a lot reflection and indeed the operation finished about 6 times faster!

If you do a lot of reflection in your projects you should definitely give a look at this code. It's worth...

3 comments:

Juri Strumpflohner said...

Interesting post. Reflection is indeed cool and is what makes programming languages powerful and more dynamic :)

I see you have again more time for posting ;)

Manfred said...

Yes, thats true :-)
Everything calms down a bit so I have more time for my blog...

Juri Strumpflohner said...

good to know :)