Question

I've been reading a lot about emit and how it's so much faster than reflection but haven't been able to find out why. I understand emit is injecting IL code but why is this faster than reflection when doing property mapping like an ORM?

Referring to this sort of use case: Emit mapper vs valueinjecter or automapper performance

Était-ce utile?

La solution

Reflection uses general purpose code and metadata to perform its actions. Reflection calls will usually do a lot of runtime checking, for example if the property you want to access really belongs to the type of the object you provided. Or that the parameters you want to pass into a method are compatible with the signature. And of course a lot of boxing and unboxing because everything is just treated as a object.

On the other hand reflection emit generates code specifically for the task you want to perform, checks a lot of things only once during compilation and will then execute as fast as every code you have written in source code.

There is obviously quite some overhead in dynamically generating code but if you do this only once and then use this code many times it will be faster in the long term. It's the same for regular expressions. You can just use them and your expression will essentially be interpreted during operations, but if you have to use the same expression many times you can specify the compiled option and the library will produce code tailored to your expression and then you can just execute it without the need to interpret the expression every time.

So in essence reflection is like interpreting code, reflection emit is (like) compiling it.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top