Val for immutable references in Kotlin - Time & Space Complexity
Let's explore how using val for immutable references affects the time complexity of Kotlin code.
We want to see if immutability changes how long the program takes to run as input grows.
Analyze the time complexity of the following code snippet.
fun sumList(numbers: List): Int {
var total = 0
for (num in numbers) {
val current = num
total += current
}
return total
}
This code sums all numbers in a list using val for immutable references inside the loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the list.
- How many times: Once for every item in the list.
As the list gets bigger, the loop runs more times, doing the same steps each time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 steps |
| 100 | About 100 steps |
| 1000 | About 1000 steps |
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 as the list gets bigger.
[X] Wrong: "Using val makes the code slower because it creates new variables every time."
[OK] Correct: val just means the reference can't change, but it doesn't add extra loops or slow down the main work. The main time depends on how many items we process.
Understanding how immutability affects performance helps you write clear and efficient code, a skill that shows you think carefully about your programs.
"What if we replaced the val inside the loop with var? How would the time complexity change?"