Why protocol-oriented design matters in Swift - Performance Analysis
When using protocol-oriented design in Swift, it is important to understand how the program's running time changes as the input grows.
We want to know how the use of protocols affects the speed of our code.
Analyze the time complexity of the following code snippet.
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 conforms to it, then draws all shapes in a list by calling their draw method.
Identify the loops, recursion, array traversals that repeat.
- 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 in a straight line with the number of shapes.
Time Complexity: O(n)
This means the time to draw all shapes grows directly with how many shapes there are.
[X] Wrong: "Using protocols makes the code slower because of extra overhead in method calls."
[OK] Correct: Protocol calls in Swift are efficient, and the main time cost comes from how many times you call the method, not the protocol itself.
Understanding how protocol-oriented design affects performance helps you write clean code without worrying about hidden slowdowns.
"What if we added nested loops inside the draw() method? How would the time complexity change?"