Procedural vs object-oriented approach in Python - Performance Comparison
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?
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 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).
As the list gets bigger, the number of additions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items, no matter the style used.
Time Complexity: O(n)
This means the time to sum numbers grows in a straight line with how many numbers there are.
[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.
Understanding how different coding styles affect time helps you explain your choices clearly and shows you know what really matters in performance.
"What if the sum method called another method inside the class for each number? How would that affect the time complexity?"