Procedural vs OOP approach in Java - 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 input?
Analyze the time complexity of the following code snippet.
// Procedural approach
void printNumbers(int n) {
for (int i = 0; i < n; i++) {
System.out.println(i);
}
}
// OOP approach
class NumberPrinter {
void print(int n) {
for (int i = 0; i < n; i++) {
System.out.println(i);
}
}
}
Both versions print numbers from 0 up to n-1, but one uses a simple function and the other uses a class method.
Look for loops or repeated actions.
- Primary operation: The for-loop that prints numbers.
- How many times: Exactly n times, once for each number.
The number of print actions grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: Doubling n doubles the work, showing a straight line growth.
Time Complexity: O(n)
This means the time to run grows directly in step with the input size.
[X] Wrong: "Using objects always makes the program slower than procedural code."
[OK] Correct: Both approaches here do the same loop, so time depends on the loop, not on using objects or not.
Understanding how code structure affects time helps you explain your choices clearly and confidently in real projects.
"What if the OOP method called another method inside the loop? How would that affect time complexity?"