0
0
Kotlinprogramming~5 mins

Properties with val and var in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Properties with val and var
O(n)
Understanding Time 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.

Scenario Under Consideration

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

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list of people to access val and modify var properties.
  • How many times: Once for each person in the list (1000 times in this example).
How Execution Grows With Input

Each person is handled one by one, so if we have more people, the work grows evenly.

Input Size (n)Approx. Operations
1010 property accesses and updates
100100 property accesses and updates
10001000 property accesses and updates

Pattern observation: The work grows directly with the number of people. Double the people, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of properties accessed or changed.

Common Mistake

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

Interview Connect

Understanding how property access and updates scale helps you explain how your code behaves with more data, a skill useful in many programming tasks.

Self-Check

"What if we added a nested loop inside celebrateBirthday() that runs a fixed number of times? How would the time complexity change?"