0
0
C++programming~5 mins

Why object-oriented programming is used in C++ - 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 the program works as it grows?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


class Item {
public:
    int value;
    Item(int v) : value(v) {}
    int getValue() { return value; }
};

int sumValues(Item items[], int n) {
    int sum = 0;
    for (int i = 0; i < n; i++) {
        sum += items[i].getValue();
    }
    return sum;
}
    

This code defines a simple object with a value and sums the values of an array of these objects.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each object in the array and calling a method.
  • How many times: Exactly once per object, so n times for n objects.
How Execution Grows With Input

As the number of objects grows, the program does more work by visiting each object once.

Input Size (n)Approx. Operations
10About 10 method calls and additions
100About 100 method calls and additions
1000About 1000 method calls and additions

Pattern observation: The work grows directly with the number of objects, so doubling objects doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as you add more objects, because it checks each one once.

Common Mistake

[X] Wrong: "Using objects always makes the program slower because of extra method calls."

[OK] Correct: The extra method calls add a small fixed cost, but the main time depends on how many objects you process, not just that you use objects.

Interview Connect

Understanding how object-oriented design affects time helps you explain your code choices clearly and shows you think about efficiency and structure together.

Self-Check

"What if the getValue() method did a complex calculation instead of just returning a value? How would the time complexity change?"