Search code examples
c#optimizationunity-game-engineinlining

Do I need to worry about inlining in Unity/C#?


For code clarity I sometimes create a function that should very obviously be inlined, be it either a wrapper, or a function that is only called in a single point, or a short function that is supposed to be called frequently and be fast.

In C I would inline it without a second thought, but in Unity/C# there's no way to do that AFAIK (this appears to be only available at .NET 4.5).

Can I trust the compiler to be smart enough to actually inline smartly, or I'd better sometimes sacrifice code clarity for performance, mistrusting the compiler?


Sure it depends case by case, premature optimization is evil, and you should profile instead of guessing. However a general overview of this subject might still be useful as a guideline, to improve upon.


Solution

  • Manually forcing in-lining in C# at compile time doesn't make much sense. When the code is run the just-in-time compiler can decide to in-line the code based on these heuristics:

    http://blogs.msdn.com/b/ericgu/archive/2004/01/29/64717.aspx

    • Methods that are greater than 32 bytes of IL will not be inlined.
    • Virtual functions are not inlined.
    • Methods that have complex flow control will not be in-lined. Complex flow control is any flow control other than if/then/else; in this case, switch or while.
    • Methods that contain exception-handling blocks are not inlined, though methods that throw exceptions are still candidates for inlining.
    • If any of the method's formal arguments are structs, the method will not be inlined.

    If you're absolutely sure that the method has to be in-lined you can use these above heurstics to make the method more appealing to in-line.

    MethodImplOptions.AggressiveInlining is mostly useful for inlining across assembly boundaries, something I do not believe the just-in-time compiler can do (but I'd have to check that).