The overhead of function calls
What you'll learn: Understand the hidden performance "cost" of jumping between functions and why small functions aren't always free.
The Cost of the Trip
In C, functions are great for organizing code. However, calling a function isn't instantaneous. Imagine you are cooking in your kitchen and realize you need a specific spice from the pantry in the hallway. You have to stop what you’re doing, walk to the pantry, find the spice, walk back, and remember exactly where you left off in the recipe.
Even if grabbing the spice takes one second, the "commute" adds extra time. In programming, this commute is called overhead.
What Happens During a Call?
When your program calls a function, the CPU performs a frantic "to-do" list behind the scenes:
- Saving the State: The CPU records the address of the current line of code so it knows where to return.
- Passing Arguments: It places your variables (arguments) into specific registers or onto a memory structure called the "stack."
- The Jump: The CPU stops executing the current code and jumps to the memory address where the function lives.
- The Return: Once finished, the CPU cleans up the stack and jumps back to the original starting point.
For a massive function that calculates complex physics, this overhead is negligible. But for a tiny function that just adds two numbers, the "commute" might actually take longer than the work itself.
Code Example: Tiny Functions
Consider a program that calls a simple addition function inside a loop that runs a million times:
#include <stdio.h>
// A tiny function with high relative overhead
int add_one(int x) {
return x + 1;
}
int main() {
int count = 0;
for (int i = 0; i < 1000000; i++) {
// The CPU "travels" to add_one and back 1,000,000 times
count = add_one(count);
}
printf("Result: %d\n", count);
return 0;
}
In the example above, the CPU spends a significant portion of its time just managing the jump back and forth rather than doing the math. When performance is critical, programmers use "Inlining" (which we will cover next) to tell the compiler to skip the commute and just paste the function's logic directly into the loop.
Key takeaway
Every function call requires extra CPU work to manage memory and jumps, which can slow down programs if tiny functions are called millions of times.