Trailing lambda convention in Kotlin - Time & Space Complexity
Let's see how using the trailing lambda style affects how many steps a program takes.
We want to know if this style changes how long the code runs as input grows.
Analyze the time complexity of the following code snippet.
fun processList(items: List<Int>, action: (Int) -> Unit) {
for (item in items) {
action(item)
}
}
// Using trailing lambda convention
processList(listOf(1, 2, 3)) { item ->
println(item)
}
This code runs an action on each item in a list, using the trailing lambda style for the action.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list.
- How many times: Once for every item in the list (n times).
Each item causes one action call, so more items mean more steps.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 actions |
| 100 | 100 actions |
| 1000 | 1000 actions |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the list gets bigger.
[X] Wrong: "Using the trailing lambda makes the code run faster."
[OK] Correct: The trailing lambda is just a style choice. It does not change how many times the loop runs or how long the program takes.
Understanding how code style choices like trailing lambdas affect performance helps you explain your code clearly and confidently.
What if the action inside the lambda also loops over the list? How would the time complexity change?