Search code examples
c#.netoptimizationinlinejit

JIT refuses to inline tiny methods


I'm missing serious optimizations because the JIT won't inline a lot of my methods.

For example lets have the following code:

static void Main(string[] args)
{
    IsControl('\0');
}

public static bool IsControl(char c)
{
    return ((c >= 0 && c <= 31) || (c >= 127 && c <= 159));
}

Produces the following after JIT compilation:

0000001f  xor         ecx,ecx 
00000021  call        FFFFFFFFFFEC9760 
00000026  mov         byte ptr [rsp+20h],al 
0000002a  nop 
0000002b  jmp         000000000000002D 
0000002d  add         rsp,38h 
00000031  rep ret 

Note that 0000001f is where I set the breakpoint. As you can see there is a call at 00000021, that is absolutely wrong. Why would such a tiny method not be qualified for inlining? For the note, this was compiled with optimization on.


Solution

  • There is no way to require the JIT compiler inline your methods, aside from using a ahead-of-time source or bytecode transformation to inline the instructions before they ever reach the JIT.

    If your algorithm is so sensitive to micro-optimizations that removing call instructions results in a substantial performance advantage, then you might consider rewriting the performance-critical sections of code in a different language that provides more extensive facilities for controlling that behavior. Based on the wording of your question, it appears that you are trying to force C# into a problem space which it was designed to avoid altogether.