The specifier inline
has two very different uses. The first is to tip the compiler that that function will probably perform better if it is replaced in the call. The second, and perhaps overlooked, is to allow the function to be defined twice. I will explain:
Suppose you have a header matematica.hpp
with the function thus:
int cubo(int n) {
return n*n*n;
}
Now create two different code files, one with the function main
and another with some other function. If both include your header, both will define a function cube
. When generating the final executable this will give problem because Linker will not know which of the two to use (even if they are identical). Adding inline
in defining this problem some. Linker merely assumes two functions inline
with the same name are equal and use one of the two without error. Ie: with the inline
you can define functions in headers. This is necessary because to effect optimization, the compiler actually needs to have function definition in all files.
Now the interesting point: compilers are smart. They will take the initiative to optimize the function with or without their tip of inline
. Similarly, the compiler can choose nay optimize if it concludes that the costs are greater than the benefits. For example, your code, whether with or without the inline
produces identical result when compiled with -O2
(optimize speed, not aggressively). But if you leave, for example, the higher function (try adding a cout
inside it) the compiler will choose not to apply the optimization in it -O2
due to the increase in code size. But, if you include the tip inline
, it will make you trusting that you have a good reason to want the inline.
But if the costs are huge (for example, inline a function of 1000 lines within one that has less than 10), the compiler will most likely refuse, even with the hint. You can still force using the following:
int cubo(int n) __attribute__((always_inline)); // Isso é específico do GCC. Não funcionará
// em qualquer outro compilador.
inline int cubo(int n) {
return n*n*n;
}
Turning now to your specific question. The inline has two good sides and a bad side. The first is to remove the need for a function call. It may seem small, but organizing the arguments and making the leap to a possibly distant code region will cost a few cycles. The second is that this allows for more optimizations in the resulting code, such as reducing 3*3*3
for 27
and save more. The downside is the code increase. If a 5-line function is optimized in 10 places, it’s 50 lines more code. And this can cause a function or the body of a loop to not fit into the processor’s code cache, and force it to have to read memory in the middle of a critical run.
Simply put: Use the inline
any function defined in a header. Use the inline
in any function that is too small and trivial. Do not use the inline
anywhere else unless you know what you’re doing and make sure it’s a performance improvement (benchmarking).