Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 685
Leopold Asperger Avatar asked Sep 20 '26 19:09

Leopold Asperger


2 Answers

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.

like image 96
Sam Harwell Avatar answered Sep 23 '26 07:09

Sam Harwell


Use the MethodImplAttribute attribute:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool IsControl(char c)
{
    return ((c >= 0 && c <= 31) || (c >= 127 && c <= 159));
}

See

http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.methodimplattribute.aspx

and

http://blogs.microsoft.co.il/sasha/2012/01/20/aggressive-inlining-in-the-clr-45-jit/

like image 28
Rico Suter Avatar answered Sep 23 '26 08:09

Rico Suter