Why protocol-oriented programming matters in Swift - Performance Analysis
When using protocol-oriented programming, it is important to understand how the program's speed changes as it uses more data or more complex types.
We want to know how the use of protocols affects the time it takes for code to run as input grows.
Analyze the time complexity of the following Swift code using protocols.
protocol Drawable {
func draw()
}
struct Circle: Drawable {
func draw() {
print("Drawing Circle")
}
}
func drawAll(shapes: [Drawable]) {
for shape in shapes {
shape.draw()
}
}
This code defines a protocol and a struct that follows it, then draws all shapes in a list by calling their draw method.
Look for loops or repeated calls that affect performance.
- Primary operation: Looping through the array of shapes and calling draw() on each.
- How many times: Once for each shape in the input array.
As the number of shapes increases, the number of draw calls grows directly with it.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 draw calls |
| 100 | 100 draw calls |
| 1000 | 1000 draw calls |
Pattern observation: The work grows evenly as the input grows; doubling shapes doubles work.
Time Complexity: O(n)
This means the time to draw all shapes grows in a straight line with the number of shapes.
[X] Wrong: "Using protocols makes the code slower because of extra overhead in method calls."
[OK] Correct: Protocol calls are optimized by Swift, and the main time cost comes from how many times you call methods, not from using protocols themselves.
Understanding how protocol-oriented code scales helps you write clean, reusable code without worrying about hidden slowdowns as your app grows.
"What if the drawAll function used recursion instead of a loop? How would the time complexity change?"