Why inline
In C++, we can add inline keyword in front of function defination (inline only works on defination, you don’t need to use inline in statement).
1 | void this_is_inline_func(); |
no inline
When we call a function, the process is
- find function defination and its address
- load from memory to stack
- execute
- pop from stack
1 | void this_is_not_inline() { |
1 | 0x0000 -> defination of this_is_not_inline |
inline
All of these steps will cost extra time. To avoid this cost, we can use inline. After we defining a function as inline, we may have multiple calls in code. When we compile the code, the compiler will change function calls to function defination, so that when execute the code, instead of wasting time finding defination and loading from memory to stack, it just executes the function logic.
1 | void this_is_inline() { |
1 | 0x0000 -> defination of this_is_inline |
Why not inline
Sounds great? But the problem is, we need to copy the defination after every calls. If the defination is very complicated, we will cost losts of memory. What’s more, if the function is complicated, the execution time >> load & pop stack time, we can ignore the inline improvement.
Suggestion
Only use inline for very simple function. Actually inline is just a recommendation rather than requirement. If the function contains loop, recursion, static, etc complex logic, the function will be treated as not-inline even if you add inline keyword.
What’s more, in class, the methods defination will be treated as inline. So only define simple methods in class, for complex methods, leave statements inside class, then define them outside class.
1 | class Object { |
#define vs inline
#define replaces the pure text in pre-complie stage, inline replaces function call with function defination in complie stage.