0
0
Swiftprogramming~5 mins

Why extensions add capability without modifying in Swift - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why extensions add capability without modifying
O(n)
Understanding Time Complexity

When we add new features to existing code using extensions, it's important to know how this affects the program's speed.

We want to see how the time to run the program changes as we add more work through extensions.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


struct NumberList {
  var numbers: [Int]
}

extension NumberList {
  func sum() -> Int {
    var total = 0
    for num in numbers {
      total += num
    }
    return total
  }
}

This code adds a new function sum() to an existing structure without changing its original code.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the numbers array to add each number.
  • How many times: Once for each item in the array.
How Execution Grows With Input

As the list of numbers grows, the time to add them all grows too.

Input Size (n)Approx. Operations
1010 additions
100100 additions
10001000 additions

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the sum() function grows in a straight line with the size of the list.

Common Mistake

[X] Wrong: "Adding a function with an extension makes the program slower overall because it changes the original code."

[OK] Correct: Extensions add new features without changing existing code, so they don't slow down what was already there. The time depends on what the new function does, not on the extension itself.

Interview Connect

Understanding how extensions add work helps you explain how your code grows and stays efficient. It shows you can add features smartly without breaking or slowing down existing parts.

Self-Check

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