Avoiding redundant calculations in loops
What you'll learn: How to speed up your programs by moving static calculations out of your loops.
The "Pack Once" Rule
Imagine you are packing for a trip. Every time you pick up a new shirt to put in your suitcase, you stop, walk to the kitchen, check the refrigerator to see if you have milk, walk back, and then pack the shirt. If you have ten shirts, you’ve checked the milk ten times. Since the milk situation didn't change while you were packing, those extra trips were a total waste of energy.
In C, we often do the same thing with loops. We ask the computer to perform a calculation inside the loop body that produces the exact same result every single time the loop runs. By moving that calculation to a variable before the loop starts, we save the CPU from doing unnecessary work.
Moving the Goalposts
A common mistake occurs when using functions or math in a loop’s condition or body that doesn't depend on the loop's counter.
Consider this inefficient code:
#include <stdio.h>
#include <string.h>
void process_string(char *text) {
// Inefficient: strlen() is called every single iteration!
for (int i = 0; i < strlen(text); i++) {
// Do something with text[i]
}
}
void optimized_process(char *text) {
// Efficient: Calculate length ONCE and store it
int length = strlen(text);
for (int i = 0; i < length; i++) {
// The computer just checks the 'length' variable now
}
}
In the first example, strlen has to count every character in the string every time the loop repeats. If the string is 10,000 characters long, the computer performs millions of unnecessary checks. In the second example, we "cache" the value in a variable called length.
Why It Matters
Modern compilers are smart and sometimes catch these for you, but they can’t catch everything—especially if the calculation involves complex math or external functions. By manually moving constants (like x = 10 * 5.5 / 2) outside your loop, you guarantee that your code runs at peak performance. If a value doesn't change while the loop is spinning, it doesn't belong inside the loop.
Key takeaway
If a calculation yields the same result every time a loop runs, move it into a variable before the loop begins.