Why object-oriented programming is used in Java - Performance Analysis
We want to understand how using object-oriented programming affects the time it takes for a program to run.
Specifically, we ask: does organizing code with objects change how fast it works as the program grows?
Analyze the time complexity of the following code snippet.
class Item {
int value;
Item(int value) {
this.value = value;
}
}
public class Main {
public static void main(String[] args) {
Item[] items = new Item[1000];
for (int i = 0; i < items.length; i++) {
items[i] = new Item(i);
}
}
}
This code creates 1000 objects and stores them in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop creating new objects
- How many times: Once for each item in the array (1000 times here)
As the number of items grows, the time to create all objects grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 object creations |
| 100 | 100 object creations |
| 1000 | 1000 object creations |
Pattern observation: Doubling the input doubles the work needed.
Time Complexity: O(n)
This means the time to run grows directly with the number of objects created.
[X] Wrong: "Using objects always makes the program slower because of extra overhead."
[OK] Correct: Creating objects takes time, but organizing code with objects helps manage complexity without changing the basic growth pattern.
Understanding how object-oriented design affects program speed helps you explain your choices clearly and shows you think about both code structure and performance.
"What if we used a nested loop to create objects inside objects? How would the time complexity change?"