Why lambdas enable functional style in Kotlin - Performance Analysis
We want to see how using lambdas affects the speed of running code in Kotlin.
Specifically, how does the program's work grow when we use lambdas in a functional style?
Analyze the time complexity of the following code snippet.
val numbers = listOf(1, 2, 3, 4, 5)
val doubled = numbers.map { it * 2 }
val filtered = doubled.filter { it > 5 }
println(filtered)
This code doubles each number in a list, then keeps only those greater than 5.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Two list traversals: one for
mapand one forfilter. - How many times: Each traversal goes through all elements once.
Each element is processed twice: once to double, once to check the filter.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 operations (2 x 10) |
| 100 | About 200 operations (2 x 100) |
| 1000 | About 2000 operations (2 x 1000) |
Pattern observation: The work grows roughly twice as fast as the input size.
Time Complexity: O(n)
This means the time to run grows directly in proportion to the number of items in the list.
[X] Wrong: "Using lambdas always makes the code slower because of extra function calls."
[OK] Correct: While lambdas add small overhead, the main work is still looping through the list, so the overall time grows linearly with input size, not worse.
Understanding how lambdas affect time helps you explain your code choices clearly and shows you know how functional style works under the hood.
"What if we combined the map and filter into one loop using a single lambda? How would the time complexity change?"