内联函数 [英] Inlining Functions
问题描述
内联是什么?
它的作用是什么?
您可以内嵌C#吗?
推荐答案
是什么
就C和C ++而言,您可以使用inline关键字告诉编译器调用例程,而无需将参数压入堆栈.相反,该函数将其机器代码插入到调用它的函数中.在某些情况下,这可以显着提高性能.
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.
危险
使用内联"(inline)可以提高速度.随内联函数大小的增加而显着减少.过度使用实际上会导致程序运行缓慢.内联一个非常小的访问器函数通常会减小代码大小,而内联一个非常大的函数则可以大大增加代码大小.
The speed benefits in using "inlining" decrease significantly as the size of the inline function increases. Overuse can actually 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.
内联C#
在C#中,内联发生在JIT编译器做出决定的JIT级别上.C#当前没有可以显式执行此操作的机制.如果您想知道JIT编译器在做什么,则可以在运行时调用: System.Reflection.MethodBase.GetCurrentMethod().Name
.如果内联方法,则它将返回调用者的名称.
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.
在C#中,您不能强制方法内联,但可以强制方法不内联.如果您确实需要访问特定的调用堆栈,并且需要删除内联,则可以使用: MethodImplAttribute
和 MethodImplOptions.NoInlining
.此外,如果方法被声明为虚拟方法,那么JIT也不会内联.其背后的原因是通话的最终目标是未知的.
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.
这篇关于内联函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!