且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“内联"的目的是什么?功能定义?

更新时间:2023-11-20 19:00:46

inline 关键字建议编译器要内联函数.通常,调用一个函数时,寄存器的当前内容被 pushed (复制)到内存中.函数返回后,它们会被弹出(复制回来).

The inline keyword suggests to the compiler that the function be inlined. Normally, when a function is called, the current contents of the registers are pushed (copied) to memory. Once the function returns, they are popped (copied back).

这花费一点时间,尽管通常如此之短,以至于无论该函数执行什么,都使该函数的调用开销相形见war.有时,在一个紧密的循环中每秒调用一个非常小的函数数千次时,所有这些函数调用的组合函数调用开销可能会加起来.在这种情况下,程序员可以建议编译器,而不是在该循环中调用函数,而是将函数的内容直接放入循环中.这样可以避免开销.

This takes a little time, though normally so little that whatever the function does dwarfs the function call overhead. Occasionally when a very small function is called thousands of times per second in a tight loop, the combined function call overhead of all those function calls can add up. In these cases, a programmer can suggest to the compiler that, rather than call the function in that loop, that the contents of the function be put in the loop directly. This avoids the overhead.

某些编译器,尤其是Microsoft Visual C ++,会忽略 inline 关键字.微软认为他们的优化器足够聪明,可以知道何时应该内联函数.对于那些真的想要内联函数的情况,Microsoft和其他供应商有时会提供专有的不,我是真的!"关键词.如果使用Visual C ++,如果我没记错的话,它是 __ forceinline .但是,如果优化器强烈感觉到内联该函数是一个糟糕的主意,那么即使是这样,也可以忽略不计.

Some compilers, notably Microsoft Visual C++, ignore the inline keyword. Microsoft believes their optimizer is smart enough to know when it should inline a function. For those cases when you really want a function to be inlined, Microsoft and other vendors sometimes provide a proprietary, "no, I really mean it!" keyword. In the case if Visual C++, it's __forceinline if I remember right. Even this, however, still can be ignored if the optimizer feels very strongly that inlining that function is a bad idea.