Why functions are first-class in Swift - Performance Analysis
We want to understand how using functions as values affects the cost of running Swift code.
Specifically, how does calling or passing functions change the number of steps the program takes?
Analyze the time complexity of the following code snippet.
func applyTwice(_ f: (Int) -> Int, to x: Int) -> Int {
return f(f(x))
}
func addOne(_ n: Int) -> Int {
return n + 1
}
let result = applyTwice(addOne, to: 5)
print(result) // 7
This code defines a function that takes another function and applies it twice to a number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the passed-in function twice.
- How many times: Exactly two calls, no loops or recursion.
Since the function calls happen a fixed number of times, the steps do not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 2 function calls |
| 100 | 2 function calls |
| 1000 | 2 function calls |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run does not increase as the input number gets bigger.
[X] Wrong: "Passing functions always makes the program slower as input grows."
[OK] Correct: Here, the function calls happen a fixed number of times, so the input size does not affect speed.
Understanding how functions as values work helps you explain code clearly and reason about performance in real projects.
"What if the function was applied inside a loop running n times? How would the time complexity change?"