0
0
Swiftprogramming~5 mins

Why protocol-oriented programming matters in Swift - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why protocol-oriented programming matters
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of shapes increases, the number of draw calls grows directly with it.

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

Pattern observation: The work grows evenly as the input grows; doubling shapes doubles work.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw all shapes grows in a straight line with the number of shapes.

Common Mistake

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

Interview Connect

Understanding how protocol-oriented code scales helps you write clean, reusable code without worrying about hidden slowdowns as your app grows.

Self-Check

"What if the drawAll function used recursion instead of a loop? How would the time complexity change?"