Base class and subclass in Swift - Time & Space Complexity
When using base classes and subclasses, it's important to see how the program's work grows as input changes.
We want to know how the time to run the code changes when we create or use many objects.
Analyze the time complexity of the following code snippet.
class Animal {
func speak() {
print("Animal sound")
}
}
class Dog: Animal {
override func speak() {
print("Bark")
}
}
let dogs = (1...n).map { _ in Dog() }
dogs.forEach { $0.speak() }
This code creates n Dog objects and calls their speak method one by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating n Dog objects and calling speak on each.
- How many times: The speak method is called once for each Dog, so n times.
As the number of Dog objects increases, the total work grows in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 speak calls |
| 100 | About 100 speak calls |
| 1000 | About 1000 speak calls |
Pattern observation: Doubling n doubles the work because each object is handled once.
Time Complexity: O(n)
This means the time grows directly with the number of objects created and used.
[X] Wrong: "Because of inheritance, the code runs slower exponentially as n grows."
[OK] Correct: Inheritance itself does not add extra loops or repeated work; each object is still handled once.
Understanding how subclassing affects time helps you explain object-oriented code performance clearly and confidently.
"What if the speak method called another method that loops over all dogs? How would the time complexity change?"