Why extensions add capability without modifying in Swift - Performance Analysis
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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the
numbersarray to add each number. - How many times: Once for each item in the array.
As the list of numbers grows, the time to add them all grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items. Double the items, double the work.
Time Complexity: O(n)
This means the time to run the sum() function grows in a straight line with the size of the list.
[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.
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.
"What if the sum() function used recursion instead of a loop? How would the time complexity change?"