0
0
Kotlinprogramming~5 mins

Custom delegated properties in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Custom delegated properties
O(n)
Understanding Time Complexity

When using custom delegated properties in Kotlin, it's important to understand how the time to get or set a property changes as your program runs.

We want to know how the cost of accessing or updating these properties grows with usage.

Scenario Under Consideration

Analyze the time complexity of the following Kotlin code using a custom delegate.


class ExampleDelegate {
    private var storedValue: String = ""

    operator fun getValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>): String {
        return storedValue
    }

    operator fun setValue(thisRef: Any?, property: kotlin.reflect.KProperty<*>, value: String) {
        storedValue = value
    }
}

class Example {
    var name: String by ExampleDelegate()
}
    

This code defines a custom delegate that stores and retrieves a string value for a property.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Each time the property name is accessed or updated, the delegate's getValue or setValue function runs.
  • How many times: Once per property access or update; no loops or recursion inside these functions.
How Execution Grows With Input

Each property access or update runs a simple function that does a single assignment or return.

Number of Accesses (n)Approx. Operations
1010 simple get or set calls
100100 simple get or set calls
10001000 simple get or set calls

Pattern observation: The time grows directly with the number of property accesses or updates, each costing about the same.

Final Time Complexity

Time Complexity: O(n)

This means the total time grows linearly with how many times you get or set the property.

Common Mistake

[X] Wrong: "Using a custom delegate makes property access slower in a way that depends on the size of stored data inside the delegate."

[OK] Correct: The delegate functions here do simple operations that take constant time regardless of stored data size, so each access or update costs about the same.

Interview Connect

Understanding how custom delegates work and their time cost helps you explain your code clearly and reason about performance in real projects.

Self-Check

What if the delegate stored data in a list and searched it on each get? How would the time complexity change?