Creating objects in Python - Performance & Efficiency
When we create objects in Python, it takes some time to set up each one.
We want to know how the time needed grows as we make more objects.
Analyze the time complexity of the following code snippet.
class Item:
def __init__(self, value):
self.value = value
items = []
n = 10 # Example value for n
for i in range(n):
items.append(Item(i))
This code creates a list of n objects, each holding a value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a new object inside the loop.
- How many times: Exactly
ntimes, once per loop cycle.
Each new object takes a little time, so total time grows as we add more.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 object creations |
| 100 | About 100 object creations |
| 1000 | About 1000 object creations |
Pattern observation: The time grows directly with the number of objects created.
Time Complexity: O(n)
This means if you double the number of objects, the time to create them roughly doubles too.
[X] Wrong: "Creating many objects happens instantly, so time doesn't grow with more objects."
[OK] Correct: Each object needs some setup time, so more objects mean more total time.
Understanding how object creation time grows helps you write efficient code and explain your choices clearly.
"What if we created objects inside a nested loop instead? How would the time complexity change?"