Why object-oriented programming is used in Python - Performance Analysis
We want to see how using object-oriented programming affects how long a program takes to run.
Specifically, we ask: does organizing code with objects change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
class Item:
def __init__(self, value):
self.value = value
n = 10 # Example input size
items = [Item(i) for i in range(n)]
for item in items:
print(item.value)
This code creates a list of objects and then goes through each object to print its value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of objects to access and print each value.
- How many times: Exactly once for each object, so n times if there are n objects.
As the number of objects grows, the time to print all values grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: Doubling the number of objects doubles the work.
Time Complexity: O(n)
This means the time grows directly with the number of objects you have.
[X] Wrong: "Using objects always makes the program slower because of extra steps."
[OK] Correct: Accessing object properties is simple and usually does not add extra loops or big delays. The main time depends on how many items you process, not on using objects.
Understanding how object-oriented code runs helps you explain your design choices clearly and shows you know how code structure affects performance.
"What if we added a nested loop inside the object method that runs for each item? How would the time complexity change?"