Small Functions Help the JIT Compiler

28 06 2011

The CLR invokes the Just In Time Compiler on a function-by-function basis. Functions that do not ever get called do not get JITed. By factoring code into more, smaller functions rather than fewer larger functions you minimize the amount of extraneous code that gets JITed.

You can see this clearly using PerfMonitor (PerfMonitor runAnalyze program.exe) which provides some JIT compilation statistics. In my experiment the difference was apparent both in overall execution time and size of the native code created.

class Program
{
    static void Main(string[] args)
    {
        TestFunction();
        TestFunction2();
    }
    static void TestFunction(int control = 0)
    {
        if(control == 0)
        {}
        else
        {
          //lots of inline code
        }
    }

    static void TestFunction2(int control = 0)
    {
        if (control == 0)
        {}
        else if (control == 1)
        {
          //lots of inline code
        }
    }
}
  • Number of methods JIT compiled: 3
  • Total Size of Native code created: 2775 bytes
  • Average Native method size compiled: 925.0 bytes
  • Ratio of JIT compilation to CPU time: 6.1%
  • Total Duration: 372 msec
class Program
{
    static void Main(string[] args)
    {
        TestFunction();
        TestFunction2();
    }

    private static void func1()
    {
       //lots of inline code
    }

    static void TestFunction(int control = 0)
    {
        if(control == 0)
        {}
        else
        {
          func1();
        }
    }

    static void TestFunction2(int control = 0)
    {
        if (control == 0)
        {}
        else if (control == 1)
        {
          func1();
        }
    }
}
  • Number of methods JIT compiled: 3
  • Total Size of Native code created: 221 bytes
  • Average Native method size compiled: 73.7 bytes
  • Ratio of JIT compilation to CPU time: 3.7%
  • Total Duration: 355 msec
Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: