0
0
Kotlinprogramming~5 mins

Why lambdas enable functional style in Kotlin - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why lambdas enable functional style
O(n)
Understanding Time Complexity

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?

Scenario Under Consideration

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 Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Two list traversals: one for map and one for filter.
  • How many times: Each traversal goes through all elements once.
How Execution Grows With Input

Each element is processed twice: once to double, once to check the filter.

Input Size (n)Approx. Operations
10About 20 operations (2 x 10)
100About 200 operations (2 x 100)
1000About 2000 operations (2 x 1000)

Pattern observation: The work grows roughly twice as fast as the input size.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to the number of items in the list.

Common Mistake

[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.

Interview Connect

Understanding how lambdas affect time helps you explain your code choices clearly and shows you know how functional style works under the hood.

Self-Check

"What if we combined the map and filter into one loop using a single lambda? How would the time complexity change?"