1

I'm struggling with ngen and generic collections. I've ngen'ed all my assemblies in solution, but still somehow jitting is occurred every time my app is executing that code:

private Dictionary<int, bool> VerifyedFunc; 

public SecurityProvider()
{
    ...
    VerifyedFunc = new Dictionary<int, bool>();
    ...       
}

MDA msg:

Managed Debugging Assistant 'JitCompilationStart' has detected a problem in '*.exe'.
Additional Information: 
<mda:msg xmlns:mda="http://schemas.microsoft.com/CLR/2004/10/mda">
<mda:jitCompilationStartMsg break="true">
<method name="mscorlib!System.Collections.Generic.Dictionary`2::.ctor"/>
</mda:jitCompilationStartMsg>
</mda:msg>

Are there are some issues with NGen and generic collections?

nikita
  • 2,737
  • 2
  • 20
  • 26

1 Answers1

9

Well, this isn't a problem. You made it a problem by using the jitCompilationStartMsg debugging assistant. That simply reports that the jitter got started. We went over this in your previous question about that MDA.

This is otherwise entirely normal and the way that generics work in .NET. The jitter generates the concrete class from the generic cookie-cutter class definition at runtime. There will be one instance of the concrete class for any reference type and one each for every value type that you use in your code.

This is not very compatible with Ngen of course, Dictionary<> is a class in mscorlib.dll and that assembly was ngen-ed when you installed .NET on your machine. Ngen is powerless to guess up front what concrete class types you are going to instantiate in your code. There is a countermeasure for this in mscorlib.dll, it pre-defines a number of generic types so they will be ngen-ed. Like List<int>, very likely to be used in an application. And in the .NET framework itself.

You can see these predeclared generic types from the Reference Source, CommonlyUsedGenericInstantiations() method. Note how it has several precooked versions of Dictionary<> in that method. But not a Dictionary<int, bool>, too unusual. So the jitter is needed to create the type for you.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • Thanks! Now I've got it! I'm just afraid of that phrase that I've read - " If only one of the modules does not have a corresponding native image, however, the mscorjit.dll will still be loaded. Then not only will the code will be JITed, consuming CPU cycles, but also many pages in the NGen images will be touched because the JIT compiler needs to read metadata. This will result in an even worse startup. For this reason, it is recommended that you remove any code that might cause JITing during startup." – nikita May 20 '13 at 12:53
  • 4
    It is important to know when to **stop** optimizing. If you are fretting over a Dictionary getting jitted then it is time to stop and call the job done. – Hans Passant May 20 '13 at 13:00