Inlining Functions
What you'll learn: How compilers eliminate function call overhead by copying a function's body directly into the call site.
Function calls aren't free. Every time your program calls a function, it must:
- Push arguments onto the stack or into registers
- Save the return address
- Jump to the function's code
- Execute the function
- Jump back to the caller
- Clean up the stack
This overhead is negligible for large functions, but for small, frequently-called functions, it can dominate execution time.
The Core Idea
Function inlining is an optimization where the compiler replaces a function call with the actual body of the function. Instead of jumping to separate code, the function's operations are copied directly into the calling location.
Before inlining:
int square(int x) {
return x * x;
}
int result = square(5) + square(6);
After inlining:
// Compiler transforms this internally to:
int result = (5 * 5) + (6 * 6);
When to Inline
Inlining works best for:
- Small functions (getters, setters, simple calculations)
- Frequently called functions (inside loops)
- Functions called from only one place
However, inlining large functions can bloat your binary and hurt performance by polluting the instruction cache. Compilers use heuristics to decide what to inline automatically.
The Benefit
By eliminating call overhead, inlined code runs faster. Additionally, inlining exposes the function's body to other optimizations like constant folding and dead code elimination that couldn't see through the function boundary.
Key Takeaway: Function inlining replaces function calls with the function's body, eliminating call overhead and enabling further optimizations, but must be balanced against code size growth.