Sunday 15 February 2009

Inline Functions in C#

What are They?

In the terms of C and C++ you use the inline keyword to tell the compiler to call a routine without the overhead of pushing parameters onto the stack. The Function instead has it's machine code inserted into the function where it was called. This can create a significant increase in performance in certain scenarios.


The speed benefits in using "inlineing" decrease significantly as the size of the inline function increases. Overuse can actaully cause a program to run slower. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size.

Inlining in C#

In C# inlining happens at the JIT level in which the JIT compiler makes the decision. There is currently no mechanism in C# which you can explicitly do this. If you wish to know what the JIT compiler is doing then you can call System.Reflection.MethodBase.GetCurrentMethod().Name at runtime. If the Method is inlined it will return the name of the caller instead.

In C# you cannot force a method to inline but you can force a method not to. If you really need access to a specific callstack and you need to remove inlining you can use : MethodImplAttribute with MethodImplOptions.NoInlining. In addition if a method is declared as virtual then it will also not be inlined by the JIT. The reason behind this is that the final target of the call is unknown.

More on inline here

No comments:

Post a Comment