Properties with val and var in Kotlin - Time & Space Complexity
Let's see how the time it takes to access or change properties grows when using val and var in Kotlin.
We want to know how the program's speed changes as we work with these properties more.
Analyze the time complexity of the following code snippet.
class Person(val name: String, var age: Int) {
fun celebrateBirthday() {
age += 1
}
}
fun main() {
val people = List(1000) { Person("Name$it", 20) }
for (person in people) {
println(person.name)
person.celebrateBirthday()
}
}
This code creates a list of people with fixed names and ages that can change. It prints each name and increases each person's age by one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the list of people to access
valand modifyvarproperties. - How many times: Once for each person in the list (1000 times in this example).
Each person is handled one by one, so if we have more people, the work grows evenly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 property accesses and updates |
| 100 | 100 property accesses and updates |
| 1000 | 1000 property accesses and updates |
Pattern observation: The work grows directly with the number of people. Double the people, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of properties accessed or changed.
[X] Wrong: "Accessing a val property is slower than a var because it cannot change."
[OK] Correct: Both val and var properties are accessed quickly; the difference is only if you can change the value, not how fast you get it.
Understanding how property access and updates scale helps you explain how your code behaves with more data, a skill useful in many programming tasks.
"What if we added a nested loop inside celebrateBirthday() that runs a fixed number of times? How would the time complexity change?"