内联函数
维基百科,自由的百科全书
在计算机科学中,内联函数(有时称作在线函数)是一种编程语言结构,用来建议编译器对一些特殊函数进行内联扩展(有时称作在线扩展);也就是说建议编译器将指定的函数体插入并取代每一处调用该函数的地方(上下文),从而节省了每次调用函数带来的额外时间开支。但在选择使用内联函数时,必须在程序占用空间和程序执行效率之间进行权衡,因为过多的对较复杂的函数进行内联扩展将带来很大的存储资源开支。另外还需要非常注意的是对递归函数的内联扩展可能带来部分编译器的无穷编译。
目录 |
[编辑] 设计内联函数的动机
内联扩展是一种特别的用于消除调用函数时所造成的固有的时间消耗方法。一般用于能够快速执行的函数,因为在这种情况下函数调用的时间消耗显得更为突出。这种方法对于很小的函数也有空间上的益处,并且它也使得一些其他的优化成为可能。
没有内联函数虽然
Without inline functions, however, the programmer has little to no control over which functions are inlined and which are not; the compiler alone makes this decision. Adding this degree of control allows application-specific knowledge, such as frequently executed functions, to be exploited in choosing which functions to inline.
Also, in some languages inline functions interact intimately with the compilation model; for example, in C++, it is necessary to define an inline function in every module that uses it, whereas ordinary functions must be defined in only a single module. This facilitates compilation of modules independently of all other modules.
[编辑] 与宏的比较
Traditionally, in languages such as C, inline expansion was accomplished at the source level using parameterized macros. Inlining provides several benefits over this approach:
- Macro invocations do not perform type checking, or even check that arguments are well-formed, whereas function calls usually do.
- Since C macros use mere textual substitution, this may result in unintended side-effects and inefficiency due to re-evaluation of arguments and order of operations.
- Compiler errors within macros are often difficult to understand, because they refer to the expanded code, rather than the code the programmer typed.
- Many constructs are awkward or impossible to express using macros, or use a significantly different syntax. In-line functions use the same syntax as ordinary functions, and can be inlined and un-inlined at will with ease.
- Debugging information for inlined code is usually more helpful than that of macro-expanded code.
Many compilers can also inline expand some recursive functions; recursive macros are typically illegal.
Bjarne Stroustrup, the designer of C++, likes to emphasize that macros should be avoided wherever possible, and advocates extensive use of inline functions.
[编辑] 语言支持
C++,C99和GNU C都支持内联函数,然而各种实际的C编译器通常不支持。在Ada中,关键字“pragma”可以用来提示内联扩展。其他的大部分编程语言,包括Java和其他功能语言,不支持内联函数,但他们的编译器常常进行强制性的内联扩展。不同的编译器在内联扩展上有处理不同复杂程度函数的能力。主流C++编译器如Visual C++和GCC提供了启用自动选择合适的函数进行内联扩展的选项,即使是对没有指定为内联函数的函数。
内联函数在C++中的写法如下:
inline int max (int a, int b) { if (a > b) return a; else return b; }
a = max (x, y); // 等价于 "a = (x > y ? x : y);"
[编辑] 对内联函数的怀疑
除了通常使用内联扩展可能带来的问题,作为一种编程语言特性的内联函数也可能并没有看起来那么有效,原因如下:
- 通常,编译器比程序设计者更清楚对于一个特定的函数是否合适进行内联扩展;一些情况下,对于程序员指定的某些内联函数,编译器可能更倾向于不使用内联甚至根本无法完成内联。
- 对于一些开发中的函数,它们可能从原来的不适合内联扩展变得适合或者倒过来。尽管内联函数或者非内联函数的转换易于宏的转换,但增加的维护开支还是使得它的优点显得更不突出了。
- 对于基于C的编译系统,内联函数的使用可能大大增加编译时间,因为每个调用该函数的地方都需要替换成函数体,代码量的增加也同时带来了潜在的编译时间的增加。
[编辑] 参见
- 内联扩展 (在线扩展)