Extension syntax in Swift - Time & Space Complexity
When we add new features to existing code using extensions, it's important to know how this affects the time it takes to run our program.
We want to understand how the extra code inside an extension changes the work the program does as input grows.
Analyze the time complexity of the following code snippet.
extension Array {
func printAll() {
for item in self {
print(item)
}
}
}
let numbers = [1, 2, 3, 4, 5]
numbers.printAll()
This code adds a new function to all arrays that prints each item one by one.
- Primary operation: A loop that goes through each item in the array.
- How many times: Once for every item in the array.
As the array gets bigger, the function prints more items, so it does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print actions |
| 100 | 100 print actions |
| 1000 | 1000 print actions |
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 function grows in a straight line with the number of items in the array.
[X] Wrong: "Adding an extension always makes the program slower in a big way."
[OK] Correct: Extensions just add code like any other function; the time depends on what the code does, not that it is in an extension.
Knowing how extensions affect time helps you explain your code clearly and shows you understand how your program grows with input size.
"What if the extension function called another function that itself loops over the array? How would the time complexity change?"