Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload all assemblies (JIT)

We are taking a hit the first time some heavy UI screens are loaded. Our project is divided into one main executable and several DLL files. The DLL files can also contain UI screens which are slow the first time they are loaded.

Is there a way (in code) we can preload all the referenced assemblies so as to avoid the JIT compilation hit?

I know there is a tool called NGen. Is it possible to operate NGen in a development environment so we can see its effects instantly? Ideally though, we would like to preload the referenced assemblies from code.

Using C# .NET 3.5 along with DevExpress for our UI components.

like image 446
Wozart Avatar asked Mar 03 '11 01:03

Wozart


1 Answers

I personally found that putting the pre-jitter in 'Program' helped in a certain application, but that is a situation-specific question.

More importantly, the code in wal's answer will crash when it encounters an abstract method, so two lines of code have been added to skip abstract methods.

static Program()
{
    foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
    {
        foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly |
                            BindingFlags.NonPublic |
                            BindingFlags.Public | BindingFlags.Instance |
                            BindingFlags.Static))
        {
            if ((method.Attributes & MethodAttributes.Abstract) == MethodAttributes.Abstract|| method.ContainsGenericParameters)
            {
                continue;
            }
            System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle);
        }
    }
    Console.WriteLine("jitted!");
}
like image 147
Cameron Avatar answered Oct 13 '22 09:10

Cameron