Why closures are fundamental in Swift - Performance Analysis
Closures let us write blocks of code that can be used later or multiple times. Understanding their time cost helps us write faster Swift programs.
We want to know how the time to run code with closures changes as we use them more or in different ways.
Analyze the time complexity of the following code snippet.
let numbers = [1, 2, 3, 4, 5]
let doubled = numbers.map { number in
return number * 2
}
print(doubled)
This code uses a closure inside the map function to double each number in an array.
- Primary operation: The closure runs once for each item in the array.
- How many times: Exactly as many times as there are items in the array.
Each new item means the closure runs one more time, so the total work grows steadily with the number of items.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 closure calls |
| 100 | 100 closure calls |
| 1000 | 1000 closure calls |
Pattern observation: The work grows in a straight line as input grows.
Time Complexity: O(n)
This means the time to run the code grows directly with the number of items processed by the closure.
[X] Wrong: "Closures always slow down code a lot because they add extra steps."
[OK] Correct: Closures themselves just run code like any function. The main time depends on how many times the closure runs, not that it is a closure.
Knowing how closures affect time helps you explain your code choices clearly and shows you understand how Swift runs your programs efficiently.
"What if the closure inside map called another function that loops over the array again? How would the time complexity change?"