Lazy evaluation vs eager evaluation in Kotlin - Performance Comparison
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?
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.
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.
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 |
|---|---|
| 10 | About 10 multiplications and 10 additions |
| 100 | About 100 multiplications and 100 additions |
| 1000 | About 1000 multiplications and 1000 additions |
Pattern observation: The total work grows directly with the number of items.
Time Complexity: O(n)
This means the time to complete grows in a straight line as the input size grows.
[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.
Understanding how lazy and eager evaluation affect time helps you explain performance choices clearly.
What if we replaced the sequence with a lazy sequence that filters out half the items before mapping? How would the time complexity change?