Why functions are first-class in Kotlin - Performance Analysis
We want to understand how using functions as first-class citizens affects the time it takes for a Kotlin program to run.
Specifically, how does calling, passing, or returning functions impact execution time as the program grows?
Analyze the time complexity of the following Kotlin code snippet.
fun applyOperation(numbers: List, operation: (Int) -> Int): List {
val result = mutableListOf()
for (number in numbers) {
result.add(operation(number))
}
return result
}
fun square(x: Int) = x * x
val nums = listOf(1, 2, 3, 4, 5)
val squared = applyOperation(nums, ::square)
This code applies a function passed as a parameter to each item in a list and returns a new list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the list and calling the passed function.
- How many times: Once for each element in the input list.
As the list size grows, the number of times the function is called grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items processed.
[X] Wrong: "Passing functions as parameters makes the program slower in a way that changes the overall time complexity."
[OK] Correct: Passing functions only adds a small fixed cost per call; the main time depends on how many times the function runs, not on the fact it is passed as a parameter.
Understanding how first-class functions affect time helps you explain your code clearly and reason about performance in real projects.
What if the passed function itself contains a loop over the input? How would that change the time complexity?