Custom delegated properties in Kotlin - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: Each time the property
nameis accessed or updated, the delegate'sgetValueorsetValuefunction runs. - How many times: Once per property access or update; no loops or recursion inside these functions.
Each property access or update runs a simple function that does a single assignment or return.
| Number of Accesses (n) | Approx. Operations |
|---|---|
| 10 | 10 simple get or set calls |
| 100 | 100 simple get or set calls |
| 1000 | 1000 simple get or set calls |
Pattern observation: The time grows directly with the number of property accesses or updates, each costing about the same.
Time Complexity: O(n)
This means the total time grows linearly with how many times you get or set the property.
[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.
Understanding how custom delegates work and their time cost helps you explain your code clearly and reason about performance in real projects.
What if the delegate stored data in a list and searched it on each get? How would the time complexity change?