0
0
Pythonprogramming~5 mins

Procedural vs object-oriented approach in Python - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Procedural vs object-oriented 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 objects instead of simple steps change how the program grows with bigger input?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


def sum_list_procedural(numbers):
    total = 0
    for num in numbers:
        total += num
    return total

class NumberList:
    def __init__(self, numbers):
        self.numbers = numbers
    def sum(self):
        total = 0
        for num in self.numbers:
            total += num
        return total

This code shows two ways to sum numbers: one with simple steps, one using a class and method.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of numbers to add each one.
  • How many times: Once for each number in the list (n times).
How Execution Grows With Input

As the list gets bigger, the number of additions grows the same way.

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

Pattern observation: The work grows directly with the number of items, no matter the style used.

Final Time Complexity

Time Complexity: O(n)

This means the time to sum numbers grows in a straight line with how many numbers there are.

Common Mistake

[X] Wrong: "Using classes always makes the program slower because of extra steps."

[OK] Correct: Both ways do the same main work of adding numbers once each, so time grows the same way.

Interview Connect

Understanding how different coding styles affect time helps you explain your choices clearly and shows you know what really matters in performance.

Self-Check

"What if the sum method called another method inside the class for each number? How would that affect the time complexity?"