Click here to Skip to main content
Click here to Skip to main content

Pre-compile (pre-JIT) your assembly on the fly, or trigger JIT compilation ahead-of-time

By , 27 Nov 2008
 

Introduction

All .NET developers know that one of the best features of the CLR is JIT-compilation: Just-In-Time compilation. Its name describes how it works: right before calling your method (just in time), the CLR triggers the JIT-compiler to produce native code from MSIL. JIT compilation is perfect for server-side applications: the JIT compiler produces highly optimized native code based on the execution environment data. The generated native code is stored in the application domain, and is used during consequent calls to this method. Though JIT compilation is not always the best choice for client-side applications with a rich user interface - users are pretty often complaining about lazy start-up of applications. In spite of developer explanations like "guys, it's JITting, we can't do anything here", users continue to complain, making our development managers unhappy. Obviously, unhappy managers tend to be unhappy developers.

So, what is the solution here? Develop the client-side application in C++ or Delphi? Some might say that we could use the Native Image Generation tool in .NET (ngen.exe). ngen.exe is not a silver bullet here, due to the following reasons:

    1. MSDN states regarding native images: Performance of native images depends on a number of factors that make analysis difficult, such as code and data access patterns, how many calls are made across module boundaries, and how many dependencies have already been loaded by other applications. The only way to determine whether native images benefit your application is by careful performance measurements in your key deployment scenarios. Let me rephrase this: it means that it does not guarantee you better performance.

    2. Native images installation/creation requires administrative privileges. This slightly reduces the set of suitable scenarios.

So, suddenly, I've come to the main point of my article. The main point is how to trigger JIT compilation in advance, how to pre-compile your assembly when it's more preferable for your application.

Let me start from an example:

Consider a scenario: We have a rich desktop client application with a huge number of different forms and and fancy UI controls (like DevExpress or Infragistics). Of course, during the first opening of each form, users are going to experience a delay due to JITting of all these fancy control libraries. How can we avoid this? We can trigger JIT compilation of heavy UI control libraries at some starting point of the application (for instance, during user log-in) in a separate background thread with a low priority. Or, we can pre-JIT all other forms while the user is working with the first one... I can imagine here a lot of Use Cases, but I am sure you can do it better in the scope of your particular project.

The code

We have a very nice namespace in BCL called System.Runtime.CompilerServices which provides advanced developers with the ability to influence runtime behavior. But, here, we need only one class from this namespace - RuntimeHelpers, and its method PrepareMethod, in particular. So, what do we do here: I just load some heavy assembly by using the Assembly.Load method (you can load it in a different way, of course), then walk through its types, and force JITting of all the methods of each type. That's it. As easy as possible. One more point, I do it in a separate low priority thread: don't worry about it, PrepareMethod is thread safe.

Thread jitter = new Thread(() =>
{
  foreach (var type in Assembly.Load("MyHavyAssembly, Version=1.8.2008.8," + 
           " Culture=neutral, PublicKeyToken=8744b20f8da049e3").GetTypes())
  {
    foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly | 
                        BindingFlags.NonPublic | 
                        BindingFlags.Public | BindingFlags.Instance | 
                        BindingFlags.Static))
    {
      System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle);
    }
  }
});
jitter.Priority = ThreadPriority.Lowest;
jitter.Start();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vitaliy Liptchinsky
Technical Lead bwin Interactive Entertainment AG
Austria Austria
Member
The views expressed in my articles are mine and do not necessarily reflect the views of my employer.
 
if(youWantToContactMe)
{
SendMessage(string.Format("{0}@{1}.com", "liptchinski_vit", "yahoo"));
}
 
More info in my LinkedIn profile:
http://www.linkedin.com/in/vitaliyliptchinsky

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralERRORSmemberseeblunt28 Nov '08 - 2:08 
Getting errors on static methods and generic paramaterised methods.
Fixed with the following alteration.
Thread jitter = new Thread(() =>
{
foreach (var type in Assembly.GetEntryAssembly().GetTypes())
{
foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly |
BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Instance ))
{
if (!method.IsAbstract && !method.IsGenericMethodDefinition && !method.ContainsGenericParameters )
{
System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle);
Console.WriteLine("{0} {1}", type.Name, method.Name);
}
}
}
});
jitter.Priority = ThreadPriority.Lowest;
jitter.Start();

GeneralRe: ERRORSmemberNicola Costantini28 Nov '08 - 2:41 
better....
 
foreach (Type type in Assembly.Load(asm.FullName).GetTypes())
{
if (type.ContainsGenericParameters)
continue;
 
Smile | :)
GeneralRe: ERRORSmemberVitaliy Liptchinsky28 Nov '08 - 3:08 
Hi Guys!
 
Thanks a lot for fixes! Smile | :)
Honestly, I haven't tested it with static and generic methods...
 
Vitaliy Liptchinsky

GeneralRe: ERRORSmemberNicola Costantini28 Nov '08 - 3:18 
your hint is great man! Even if I'm thinking about compiling in native code to speed up!! Laugh | :laugh:
QuestionBenchmarks?mvpGiorgi Dalakishvili27 Nov '08 - 21:00 
Hello,
 
It would be nice to see some benchmarks to compare time needed to load an application with the method you described and without it.
 

AnswerRe: Benchmarks?memberjohannesnestler27 Nov '08 - 21:38 
Just tried it and the time to load the application is nearly the same, but the performance of loaded Forms and TabPages is great during their first call. You can see it with your eye-brain-benchmark-timer Big Grin | :-D
GeneralRe: Benchmarks?mvpGiorgi Dalakishvili27 Nov '08 - 21:48 
It would be nice if the author provided demo project.
 

GeneralRe: Benchmarks?memberVitaliy Liptchinsky27 Nov '08 - 22:00 
Hello Georgi,
 
Why do you need benchmarks? I haven't provided demo project because I believe it is obvious thing: performance difference when you have to JIT and performance difference when you don't. Smile | :)
 
Vitaliy Liptchinsky

GeneralRe: Benchmarks?mvpGiorgi Dalakishvili27 Nov '08 - 22:21 
Yes, I agree that it's obvious but articles at codeproject usually have source code and demo project attached Smile | :)
 

GeneralVery Good!memberjohannesnestler27 Nov '08 - 21:00 
Cool | :cool: Rose | [Rose]

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 27 Nov 2008
Article Copyright 2008 by Vitaliy Liptchinsky
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid