Calling super for parent behavior in Swift - Time & Space Complexity
When a method calls super, it runs code from its parent class. We want to see how this affects the time it takes to run.
How does calling super change the work done as input grows?
Analyze the time complexity of the following code snippet.
class Parent {
func process(items: [Int]) {
for item in items {
print(item)
}
}
}
class Child: Parent {
override func process(items: [Int]) {
super.process(items: items)
print("Done")
}
}
This code shows a child class calling its parent's method using super. The parent loops over items, and the child adds a print after.
Look for loops or repeated actions.
- Primary operation: The
forloop in the parent method that prints each item. - How many times: Once for each item in the input array.
As the number of items grows, the loop runs more times.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 prints |
| 100 | About 100 prints |
| 1000 | About 1000 prints |
Pattern observation: The work grows directly with the number of items. More items mean more prints.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Calling super adds extra loops or makes the code slower in a complex way."
[OK] Correct: The super call just runs the parent's code once. It doesn't add hidden loops or multiply work beyond what the parent already does.
Understanding how super affects time helps you explain code behavior clearly. It shows you can think about inherited code and its cost, a useful skill in real projects.
What if the child method added its own loop over the items before calling super? How would the time complexity change?