Open In App

Function Inlining

Last Updated : 25 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisite: Phases of Compiler

The fifth phase of a compiler is code optimization. This phase applies various optimization techniques to the intermediate code to improve the performance of the generated machine code. Function inlining is used to improve the performance of the code.

In function inlining, the function call is replaced by the code of the function being called. Function inlining should be applied to small functions only. With the help of function inlining, we can reduce the execution time. It reduces the function call overhead and saves the time of pushing the function into and out of the stack.

32.png

Before function inlining

32.png

After function inlining

Function inlining helps in enabling more optimizations. With the help of inlined code, code optimizations like copy propagation and constant folding can be applied easily. Thus reducing the execution time.

C++




int multiply(int a,int b)  //called function
{
  return a*b;
}
int func(int x,int y)      //calling function
{
  return multiply(x,y);   //function call
}
  
//after function inlining
int func(int x,int y)
{
  return x*y;           //function call replaced with called function
}


In the above example, we are performing multiplication in function func() by passing the variables to multiply(). This increases execution time as we have to pass the variables to a separate which performs computation and returns the multiplied vale.

To simplify this, we will apply function inlining and will replace the function call with the called function’s body. This helps in saving the extra computation time and performs the same task of multipling the same numbers.

Advantages of Function Inlining

  • Faster execution of code
  • Reduces time complexity
  • Improves cache utilization
  • Reduction in code size
  • Enables additional optimizations like constant propagation or constant folding

Disadvantages of Function Inlining

  • Increase in code size
  • Compilation time increased
  • Reduced code maintainability
  • Increases space complexity

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads