Lazy property delegation in Kotlin - Time & Space Complexity
Let's explore how the time needed to get a lazy property changes as we use it more.
We want to know how the program's work grows when accessing a lazy property multiple times.
Analyze the time complexity of the following code snippet.
class Example {
val lazyValue: String by lazy {
println("Computing the value...")
"Hello"
}
}
fun main() {
val example = Example()
println(example.lazyValue)
println(example.lazyValue)
}
This code defines a lazy property that computes its value only once when first accessed, then returns the stored value on later accesses.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The lazy block runs once to compute the value.
- How many times: The computation happens only once, but the property is accessed multiple times.
When you access the lazy property the first time, it does the work to create the value. Later accesses just return the saved result quickly.
| Number of Accesses (n) | Approx. Operations |
|---|---|
| 1 | 1 computation + 1 return |
| 10 | 1 computation + 9 returns |
| 1000 | 1 computation + 999 returns |
Pattern observation: The heavy work happens once, then the cost stays very low no matter how many times you access it.
Time Complexity: O(1)
This means accessing the lazy property takes constant time after the first computation, no matter how many times you use it.
[X] Wrong: "The lazy block runs every time I access the property."
[OK] Correct: The lazy block runs only once; after that, the stored value is returned instantly without repeating the work.
Understanding lazy property delegation helps you explain how to save time by doing work only when needed and only once, a useful skill in many coding situations.
"What if the lazy property was accessed from multiple threads at the same time? How would that affect the time complexity?"