Procedural vs OOP approach in C++ - Performance Comparison
We want to see how the way we organize code affects how long it takes to run.
Does using procedures or objects change how the program grows with bigger inputs?
Analyze the time complexity of these two approaches to sum numbers.
// Procedural approach
int sumArray(int arr[], int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
return sum;
}
// OOP approach
class ArraySum {
public:
int sum(int arr[], int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += arr[i];
}
return total;
}
};
Both add up all numbers in an array, but one uses a simple function, the other uses a class method.
Look at what repeats in both codes.
- Primary operation: Loop through the array to add each number.
- How many times: Exactly once for each item in the array (n times).
As the array gets bigger, the time to add all numbers grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Doubling the input doubles the work. Both ways grow the same way.
Time Complexity: O(n)
This means the time to finish grows directly with the number of items to add.
[X] Wrong: "Using classes always makes the program slower."
[OK] Correct: Here, both ways do the same work once per item, so speed is about the same. Classes organize code but don't add extra loops.
Understanding how different coding styles affect speed helps you write clear and efficient code. It shows you can think about both design and performance.
"What if the OOP method called another method inside the loop? How would that change the time complexity?"