0
0
Kotlinprogramming~5 mins

Lazy property delegation in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Lazy property delegation
O(1)
Understanding Time 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.

Scenario Under Consideration

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

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.
How Execution Grows With Input

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
11 computation + 1 return
101 computation + 9 returns
10001 computation + 999 returns

Pattern observation: The heavy work happens once, then the cost stays very low no matter how many times you access it.

Final Time Complexity

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.

Common Mistake

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

Interview Connect

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.

Self-Check

"What if the lazy property was accessed from multiple threads at the same time? How would that affect the time complexity?"