0
0
Javaprogramming~5 mins

Why object-oriented programming is used in Java - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why object-oriented programming is used
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

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)
How Execution Grows With Input

As the number of items grows, the time to create all objects grows in a straight line.

Input Size (n)Approx. Operations
1010 object creations
100100 object creations
10001000 object creations

Pattern observation: Doubling the input doubles the work needed.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly with the number of objects created.

Common Mistake

[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.

Interview Connect

Understanding how object-oriented design affects program speed helps you explain your choices clearly and shows you think about both code structure and performance.

Self-Check

"What if we used a nested loop to create objects inside objects? How would the time complexity change?"