0
0
C++programming~5 mins

Procedural vs OOP approach in C++ - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Procedural vs OOP approach
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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.

Identify Repeating Operations

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

As the array gets bigger, the time to add all numbers grows in a straight line.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

Doubling the input doubles the work. Both ways grow the same way.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items to add.

Common Mistake

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

Interview Connect

Understanding how different coding styles affect speed helps you write clear and efficient code. It shows you can think about both design and performance.

Self-Check

"What if the OOP method called another method inside the loop? How would that change the time complexity?"