Inline replacement

from Wikipedia, the free encyclopedia

The inline expansion is an optimization method of compilers to increase the execution speed of a computer program . The code of the function to be called is copied instead of the call. This reduces the additional effort for the call (saving the registers , preparing the stack ), improves the locality and, furthermore, the code of both functions can be taken into account together when optimizing .

example

The following source text in C ...

inline int quadrat(int x) {
   return x*x;
}

int c(int a, int b) {
   return quadrat(a) + quadrat(b);
}

... can be translated by the compiler in such a way that the function is not called but the function definition is inserted directly. This behavior is optional; it can also be triggered without specifying the keyword inline by the brevity of the function quadrat (...). The same thing can happen with the simple function c () itself, i. H. this can also be linked.

Furthermore, the recommended inlining is not an optimization by the compiler, but one by the programmer.

int c(int a, int b) {
   return a*a + b*b;
}

Inline replacements can partly take over the function of macros in C , but they also offer the security of a static type check as with functions. Since this is now often undesirable (generic programming), it has usually been formulated as follows since C ++ 98:

template <class T>
T quadrat(T x) {
   return x*x;
}

template <class T>
T c(T a, T b) {
   return quadrat(a) + quadrat(b);
}

It must be declared explicitly and can be used for class independent functions as well as for member functions (methods). In the internals of the compiler, however, macros and inline substitutions cannot be compared.

However, it is not possible for the compiler to carry out the replacement desired by the programmer for every arbitrarily complex function. The function does not have to be complicated in order not to be able to replace it. Example:

inline double fact(int x) {
   return x > 1 ? x*fact(x-1) : 1;
}

The normal function call is then retained. Rather, this is to be seen inline in the example as a recommendation to the compiler, which it does not have to follow. In C ++ in particular, there are also compiler-specific stronger variants of inline (such as __forceinline) for exceptional cases , but their use can be at the expense of portability . Without such variants, however, the inline attribute is ignored by most modern compilers, at least at high optimization levels.

Some compilers can also independently identify and replace functions suitable for inline replacement in the optimization phase. In the Eiffel programming language, for example, only this automatic inline replacement is provided.