The
inline
keyword (or implicitly inlining class member functions by giving them bodies within the class) is a hint to the compiler that you want to inline the function.
The compiler may or may not choose to ignore this hint and might inline a function you did not mark to be inlined... or it might not inline a function you wanted to be inlined. It depends on how the program is to be optimized. That said... giving the inline hint can help the optimizer determine the best route to take.
As for what an inlined function actually does.... it basically copy/pastes the code into the code that calls it. For a trivial example:
1 2 3 4 5 6 7 8 9
|
inline int add(int a, int b)
{
return a+b;
}
int main()
{
cout << add(4,5);
}
|
If 'add' is inlined, the body of the 'add' function will replace the 'add' call in main. So conceptually you'd be left with something like this:
1 2 3 4
|
int main()
{
cout << (4+5);
}
|
This is the first benefit of inline functions:
It eliminates the work of calling a separate function. The computer does not have to jump to a separate area of code to do a task... instead the code for that task is inlined.
This also opens up the possibility for another optimization. The above example:
1 2 3 4
|
int main()
{
cout << (4+5);
}
|
Could then be optimized even further as this:
1 2 3 4
|
int main()
{
cout << 9;
}
|
So that's another benefit:
call-specific optimizations that could not be made if the code were in a separate function can be made when the code is inlined.
These two benefits can improve performance.
The
downside is that if the inline function is large, you're copy/pasting lots of code... which might make the program (exe) size bigger.
If the code is in a separate function, that code only exists in the program once and is 'jumped to' at each call. If that function is inlined, then the code is duplicated for each time its called.
Bigger exes can be slower exes due to cache misses and other memory access issues.
So as with any performance technique... it's a tradeoff. And the best approach depends on the situation. There is no best answer that applies to all situations.
That said... generally if a function is very very short (one or 2 lines) it can be inlined without ill consequences.