Var for mutable references in Kotlin - Time & Space Complexity
Let's see how using var for mutable references affects how long a program takes to run.
We want to know how the program's steps grow when we change the input size.
Analyze the time complexity of the following code snippet.
fun sumList(numbers: List): Int {
var total = 0
for (num in numbers) {
total += num
}
return total
}
This code adds up all numbers in a list using a mutable variable total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop that goes through each number in the list. - How many times: Once for every item in the list.
As the list gets bigger, the program does more additions, one for each number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 additions |
| 100 | 100 additions |
| 1000 | 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the list size.
[X] Wrong: "Using var makes the code slower because it changes values."
[OK] Correct: Changing a variable's value itself doesn't add extra loops or steps. The main time cost is from how many times the loop runs, not from using var.
Understanding how mutable variables work helps you explain how your code runs step-by-step, which is a useful skill in interviews and real projects.
What if we replaced the for loop with a recursive function? How would the time complexity change?