Some notes on function inlining in C and C++. This post will be continuously updated.
Why do you need to inline function calls?
- there is overhead with function call, copying the arguments of the function on the stack, transfer control to the specified function, stores the return value in a predefined location /register, and finally returning the control back to the calling function. If there is very little work done in the function, then the overhead can significantly outweigh the actual useful work.
- Furthermore, function inlining allows the compiler to do more optimizations across the boundaries of the function calls. For example, if a function call is just reading an element of an array, then inlining the function can allow vectorization.
Cases that will likely to be inlined
- function is declared with the body in the header file. This is how header libraries work.
- static inline functions are very likely to be inlined with a few constraints.
Cases that will unlikely to be inlined
- If only the prototype of a function is in the header file, but the body of the function is not, then it is very hard for the function to be inlined.