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

后端 未结 3 1303
清歌不尽
清歌不尽 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:09

    NGen should be run on each machine at install time. Make it part of your install process. That will compile for the relevant architecture.

    If your delay is indeed due to JITting, this should solve it. Profile your application to be sure.

    0 讨论(0)
  • 2021-01-06 17:20

    My first solution was to manually create dummy instances of classes and then call the methods with an optional dummy bool variable which would be false by default. This worked but required adding this dummy to every method which is crude and time consuming.

    Lucas Trzesniewski's answer is far more through as it prepares all classes and all methods in the code and it does not require any changes to any of my code so it is much easier to implement. The only cost is that by being so thorough it takes longer to complete at about .5 to 1.5 seconds or maybe .5 to 1 second longer than my selective start-up. More than worth it in my case to ensure no delays happen in code.

    There was no noticeable spike in memory or CPU usage other than the initial start-up, and memory usage actually slightly decreased, possibly because all code is now complied and optimized.

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
提交回复
热议问题