2

I'm working on a Json serialization solution.

I found out that the serialization based on emitting was much faster than direct operations on Reflection api after the emitted code had already been run once(each time with different data).

Obviously the problem is JIT. This can be verified if you check the implementation of Runtime.CompilerServices.RuntimeHelpers._CompileMethod in DynamicMethod.CreateDelegate, which is a QCall method. It only generates a Prestub for the MethodDescriptor of DynamicMethod.

So I wonder wether there is a way to force the compilation of DynamicMethod. The PreJIT feature,provided by Runtime.CompilerServices.RuntimeHelpers.PrepareMethod, simply doesn‘t work because I have no direct access to RuntimeMethodHandle of DynamicMethod. So is there other (legal) way to achieve this goal?

Thanks in advance.

  • The usual approach is to simply make sure you don't generate `DynamicMethod`s more than necessary. Caching serializers wholesale for individual types (in a `static` collection) should be enough to ensure you only incur the JIT penalty once. (You'll incur it once no matter how you slice it, of course, even if you pre-compile it at some other time, unless you go full AOT code generation with output assemblies.) – Jeroen Mostert Jan 27 '20 at 14:25
  • @JeroenMostert I choose to use hack finally, getting **RuntimeMethodHandle** by reflection. The summary of **MethodHandle** property mentions the only concern is that **RuntimeMethodHandle** is ValueType, which GC cannot track. So it will be safe to do so since we always do it before DynamicMethod gets collected(it's cached till the end of program). – HexJacaranda Jan 29 '20 at 14:01

0 Answers0