Reusability and maintenance - Time & Space Complexity
When we write reusable and maintainable code, we want to know how it affects how long the program takes to run.
We ask: does making code reusable change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int data[] = {1, 2, 3, 4, 5};
printArray(data, 5);
return 0;
}
This code uses a reusable function to print elements of an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside
printArraythat goes through each array element. - How many times: It runs once for each element in the array, so
sizetimes.
As the array gets bigger, the loop runs more times, directly matching the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
Pattern observation: The number of steps grows evenly as the input size grows.
Time Complexity: O(n)
This means the time to run grows in a straight line with the size of the input.
[X] Wrong: "Making code reusable always makes it slower or more complex."
[OK] Correct: Reusable code often just wraps the same steps in a function, so the main work still grows the same way with input size.
Understanding how reusable functions affect time helps you write clean code without worrying about hidden slowdowns.
"What if the reusable function called another function inside a nested loop? How would the time complexity change?"