0
0
Swiftprogramming~5 mins

POP vs OOP decision patterns in Swift - Performance Comparison

Choose your learning style9 modes available
Time Complexity: POP vs OOP decision patterns
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

Look at what repeats when the program runs.

  • Primary operation: The loop in renderAll that calls draw() on each shape.
  • How many times: Once for each shape in the input array.
How Execution Grows With Input

As the number of shapes grows, the number of draw calls grows the same way.

Input Size (n)Approx. Operations
1010 draw calls
100100 draw calls
10001000 draw calls

Pattern observation: The work grows directly with the number of shapes. Double the shapes, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw all shapes grows in a straight line with how many shapes there are.

Common Mistake

[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.

Interview Connect

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.

Self-Check

What if the draw method itself contained a loop over many points? How would that change the overall time complexity?