.NET Release code very slow when running a method for the first time. How to fix it withough NGen?

后端 未结 3 1302
清歌不尽
清歌不尽 2021-01-06 16:48

I have deployed a application in release mode (x64) which I expected to be fast, and I noticed that there is a severe slowdown whenever a new method, or set of methods is ex

3条回答
  •  孤城傲影
    2021-01-06 17:25

    Wow. Such delays are unusual for the JIT. Profile your app to make sure the bottleneck is the JIT.

    Now, if it's really the JIT, here's a much better method than adding a dummy argument everywhere:

    Use RuntimeHelpers.PrepareMethod on each non-generic method. This function will force the JIT to process it.

    You can also use RunClassConstructor method on each class to... well, run their static constructors.

    Here's some (totally untested) code:

    foreach (var type in Assembly.GetExecutingAssembly().GetTypes())
    {
        if (type.IsGenericTypeDefinition || type.IsInterface)
            continue;
    
        RuntimeHelpers.RunClassConstructor(type.TypeHandle);
    
        foreach (var method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly))
            RuntimeHelpers.PrepareMethod(method.MethodHandle);
    }
    

提交回复
热议问题