Inline Optimization
Inline Optimization
Inline Optimization in C++: Using Lambda for Small Operations
Prerequisites
1. Why Function Calls Matter
Function calls are not free.
In tight loops or small operations, this overhead becomes significant.
Each call may involve:
- Stack frame setup
- Parameter passing
- Jump instruction (branch)
For very small operations, avoid function call overhead by using inline functions or lambdas
2. Inline Function
Example
1
2
3
4
inline int add(int a, int b)
{
return a + b;
}
Compiler may replace function call with actual code
inlineis a hint, not a guarantee- Compiler decides based on optimization level
3. Lambda for Inline Behavior
✔ Example
1
2
3
4
5
6
auto add = [](int a, int b)
{
return a + b;
};
int result = add(1, 2);
Often inlined by compiler. No function call overhead in optimized builds
4. How to use
4-1. Small Operations
❌ Function Call Overhead
1
2
3
4
5
6
7
8
9
int square(int x)
{
return x * x;
}
for (int i = 0; i < N; i++)
{
sum += square(i);
}
Inline / Lambda
1
2
3
4
5
6
7
8
9
auto square = [](int x)
{
return x * x;
};
for (int i = 0; i < N; i++)
{
sum += square(i);
}
Compiler likely inlines → no call overhead
4-2. When NOT to Use
❌ Large functions
❌ Complex logic
❌ Recursion
Inlining large code may:
- Increase binary size
- Hurt instruction cache
This post is licensed under CC BY 4.0 by the author.