0
0
Swiftprogramming~5 mins

Why protocol-oriented design matters in Swift - Performance Analysis

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

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.

Scenario Under Consideration

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 Repeating Operations

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.
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 in a straight line with the number of shapes.

Final Time Complexity

Time Complexity: O(n)

This means the time to draw all shapes grows directly with how many shapes there are.

Common Mistake

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

Interview Connect

Understanding how protocol-oriented design affects performance helps you write clean code without worrying about hidden slowdowns.

Self-Check

"What if we added nested loops inside the draw() method? How would the time complexity change?"