Passing lambdas to functions in Kotlin - Time & Space Complexity
When we pass lambdas (small blocks of code) to functions, it's important to see how this affects the time the program takes to run.
We want to know how the number of times the lambda runs changes as the input grows.
Analyze the time complexity of the following code snippet.
fun applyToList(numbers: List, action: (Int) -> Unit) {
for (number in numbers) {
action(number)
}
}
fun main() {
val nums = listOf(1, 2, 3, 4, 5)
applyToList(nums) { println(it) }
}
This code runs a given lambda on each item in a list, printing each number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that goes through each item in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the lambda runs more times, once per item.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 lambda calls |
| 100 | 100 lambda calls |
| 1000 | 1000 lambda calls |
Pattern observation: The number of operations grows directly with the size of the list.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items.
[X] Wrong: "Passing a lambda makes the code run slower in a way that multiplies the work."
[OK] Correct: The lambda runs once per item, just like any code inside the loop. It doesn't add hidden extra loops or repeats.
Understanding how lambdas affect time helps you explain your code clearly and shows you know how to reason about performance in real projects.
"What if the lambda itself contains a loop over the list? How would the time complexity change?"