Observable property delegation in Kotlin - Time & Space Complexity
We want to understand how the time it takes to run code with observable property delegation changes as we use it more.
Specifically, how does the cost grow when the property changes many times?
Analyze the time complexity of the following code snippet.
import kotlin.properties.Delegates
class User {
var name: String by Delegates.observable("") { prop, old, new ->
println("Property ${'$'}{prop.name} changed from ${'$'}old to ${'$'}new")
}
}
fun main() {
val user = User()
repeat(5) { i ->
user.name = "Name ${'$'}i"
}
}
This code uses observable delegation to watch changes to the name property and prints a message each time it changes.
- Primary operation: The
repeat(5)loop that changes the property 5 times. - How many times: The observable callback runs once for each property change, so 5 times.
Each time the property changes, the observable callback runs once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 property changes and 10 callback calls |
| 100 | 100 property changes and 100 callback calls |
| 1000 | 1000 property changes and 1000 callback calls |
Pattern observation: The work grows directly with the number of property changes.
Time Complexity: O(n)
This means the time to run grows in a straight line with how many times the property changes.
[X] Wrong: "The observable callback runs only once no matter how many times the property changes."
[OK] Correct: The callback runs every time the property changes, so the cost adds up with each change.
Understanding how observable properties affect performance helps you write responsive and efficient Kotlin code, a useful skill in many projects.
What if we added multiple observable properties in the same class? How would the time complexity change when changing all of them?