Protocol extensions with default implementations in Swift - Time & Space Complexity
We want to understand how the time it takes to run code changes when using protocol extensions with default implementations in Swift.
Specifically, we ask: How does adding default methods in protocol extensions affect the speed as the program runs?
Analyze the time complexity of the following code snippet.
protocol Greetable {
func greet()
}
extension Greetable {
func greet() {
print("Hello from default implementation")
}
}
struct Person: Greetable {}
let n = 10
let people = Array(repeating: Person(), count: n)
for person in people {
person.greet()
}
This code defines a protocol with a default greet method, creates many Person instances, and calls greet on each.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the
greet()method on eachPersoninstance. - How many times: Exactly once for each element in the
peoplearray, which hasnelements.
As the number of people grows, the number of greet calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greet calls |
| 100 | 100 greet calls |
| 1000 | 1000 greet calls |
Pattern observation: The work grows directly with the number of items. Double the items, double the calls.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of elements we process.
[X] Wrong: "Using protocol extensions with default methods makes the code slower because it adds extra layers."
[OK] Correct: The default method is called just like any other method, so the time to run depends mainly on how many times you call it, not on it being a default implementation.
Understanding how default methods in protocols affect performance helps you write clean, reusable code without worrying about hidden slowdowns.
"What if the greet method was overridden in Person with a more complex operation? How would the time complexity change?"