0
0
Kotlinprogramming~5 mins

Lazy evaluation vs eager evaluation in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Lazy evaluation vs eager evaluation
O(n)
Understanding Time Complexity

We want to see how lazy and eager evaluation affect how long a program takes to run.

Specifically, how does the way values are computed change the work done as input grows?

Scenario Under Consideration

Analyze the time complexity of the following Kotlin code using lazy and eager lists.


val eagerList = (1..n).map { it * 2 }
val lazySequence = (1..n).asSequence().map { it * 2 }
val eagerSum = eagerList.sum()
val lazySum = lazySequence.sum()
    

This code creates a list eagerly and a sequence lazily, then sums their values.

Identify Repeating Operations

Look at what repeats when processing the numbers.

  • Primary operation: Multiplying each number by 2 and summing all numbers.
  • How many times: Exactly once for each number from 1 to n.
How Execution Grows With Input

Both eager and lazy methods do the same amount of work for n numbers, but when they do it differs.

Input Size (n)Approx. Operations
10About 10 multiplications and 10 additions
100About 100 multiplications and 100 additions
1000About 1000 multiplications and 1000 additions

Pattern observation: The total work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Lazy evaluation always makes the program faster."

[OK] Correct: Lazy evaluation delays work but does not reduce the total amount of work needed.

Interview Connect

Understanding how lazy and eager evaluation affect time helps you explain performance choices clearly.

Self-Check

What if we replaced the sequence with a lazy sequence that filters out half the items before mapping? How would the time complexity change?