Why immutability by default matters in Kotlin - Performance Analysis
We want to see how choosing immutability by default affects how long a program takes to run.
Does making data unchangeable slow down or speed up our code as it grows?
Analyze the time complexity of the following Kotlin code using immutable lists.
fun addElementImmutable(list: List, element: Int): List {
return list + element
}
fun main() {
var numbers = listOf(1, 2, 3)
numbers = addElementImmutable(numbers, 4)
println(numbers)
}
This code adds an element to a list without changing the original list, creating a new list each time.
Look at what repeats when adding elements immutably.
- Primary operation: Copying the entire list to create a new one with the added element.
- How many times: Once per addition, the whole list is copied.
As the list gets bigger, copying it takes more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 copy steps |
| 100 | About 100 copy steps |
| 1000 | About 1000 copy steps |
Pattern observation: The time to add grows directly with the list size because it copies all elements each time.
Time Complexity: O(n)
This means adding an element takes longer as the list grows, because it copies the whole list every time.
[X] Wrong: "Adding an element to an immutable list is always fast because nothing changes."
[OK] Correct: Even though the original list stays the same, the program must copy all elements to make a new list, which takes more time as the list grows.
Understanding how immutability affects time helps you explain trade-offs clearly and write safer, predictable code in real projects.
What if we used a persistent data structure that shares parts of the list instead of copying everything? How would the time complexity change?