Protocol composition in practice in Swift - Time & Space Complexity
When using protocol composition in Swift, it is important to understand how the program's work grows as input changes.
We want to know how combining multiple protocols affects the time it takes to run code that uses them.
Analyze the time complexity of the following code snippet.
protocol A {
func doA()
}
protocol B {
func doB()
}
func performAction(item: A & B) {
item.doA()
item.doB()
}
This code defines two protocols and a function that takes an item conforming to both. It calls methods from both protocols.
Look for repeated work inside the function when called with different inputs.
- Primary operation: Calling two methods on the item.
- How many times: Each method is called once per function call.
The function calls two methods regardless of input size. If the methods themselves do not loop, the work stays the same.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 |
| 100 | 2 |
| 1000 | 2 |
Pattern observation: The total work stays constant regardless of input size.
Time Complexity: O(1)
This means the time to run stays constant regardless of input size.
[X] Wrong: "Using protocol composition makes the function slower because it combines protocols."
[OK] Correct: Protocol composition itself does not add extra loops or repeated work; it just requires the item to meet multiple requirements.
Understanding how protocol composition affects performance helps you write clear and efficient Swift code, a useful skill in many coding situations.
"What if the methods doA() and doB() each contained loops over the input? How would that change the time complexity?"