POP vs OOP decision patterns in Swift - Performance Comparison
When choosing between Protocol-Oriented Programming (POP) and Object-Oriented Programming (OOP), it's important to understand how the program's work grows as it runs.
We want to see how the decision pattern affects the speed when the program handles more data or tasks.
Analyze the time complexity of this Swift example using POP and OOP patterns.
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() { print("Drawing Circle") }
}
class Square: Drawable {
func draw() { print("Drawing Square") }
}
func renderAll(shapes: [Drawable]) {
for shape in shapes {
shape.draw()
}
}
This code uses a protocol to define a drawing action, then classes implement it. The renderAll function calls draw on each shape.
Look at what repeats when the program runs.
- Primary operation: The loop in
renderAllthat callsdraw()on each shape. - How many times: Once for each shape in the input array.
As the number of shapes grows, the number of draw calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 draw calls |
| 100 | 100 draw calls |
| 1000 | 1000 draw calls |
Pattern observation: The work grows directly with the number of shapes. Double the shapes, double the work.
Time Complexity: O(n)
This means the time to draw all shapes grows in a straight line with how many shapes there are.
[X] Wrong: "Using protocols (POP) always makes the program slower than classes (OOP)."
[OK] Correct: Both POP and OOP here call the draw method once per shape, so the time grows the same way. The choice affects design more than speed in this case.
Understanding how your design choice affects performance shows you think about both code quality and speed. This skill helps you write clear, efficient programs that grow well with more data.
What if the draw method itself contained a loop over many points? How would that change the overall time complexity?