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?
Practice
val for variables by default instead of var?Solution
Step 1: Understand Kotlin's default variable behavior
Kotlin usesvalby default to create immutable variables that cannot be changed after assignment.Step 2: Recognize benefits of immutability
Immutable variables prevent accidental changes, making code safer and easier to read and maintain.Final Answer:
Becausevalcreates immutable variables, making code safer and easier to understand. -> Option AQuick Check:
Immutability = safer code [OK]
- Thinking val allows value changes
- Believing var is deprecated
- Assuming val is faster than var
Solution
Step 1: Identify Kotlin syntax for immutable variables
Kotlin usesvalto declare immutable variables that cannot be reassigned.Step 2: Check each option
val name = "Alice" usesvalcorrectly. var name = "Alice" usesvarwhich is mutable. The other two options use invalid syntax.Final Answer:
val name = "Alice" -> Option BQuick Check:
Immutable variable syntax = val [OK]
- Using var instead of val for immutability
- Trying to use 'immutable' keyword
- Combining const and var incorrectly
val x = 10 // x = 20 println(x)
Solution
Step 1: Understand the code behavior
The variablexis declared withval, so it is immutable and cannot be reassigned.Step 2: Analyze the commented reassignment
The reassignmentx = 20is commented out, so it does not run. The value ofxremains 10.Final Answer:
10 -> Option CQuick Check:
Immutable val keeps value 10 [OK]
- Assuming commented code runs
- Thinking val variables can be reassigned
- Confusing compilation and runtime errors
val count = 5 count = 10 println(count)
Solution
Step 1: Check variable declaration
countis declared withval, making it immutable.Step 2: Analyze reassignment
Trying to assigncount = 10causes a compilation error becausevalvariables cannot be reassigned.Final Answer:
Compilation error: val cannot be reassigned -> Option DQuick Check:
val reassignment = compilation error [OK]
- Thinking val variables can be reassigned
- Confusing runtime and compilation errors
- Assuming semicolons are required in Kotlin
val users = listOf("Anna", "Bob", "Cara")Solution
Step 1: Understand immutability of variable and list
valmeans the reference cannot change, andlistOfcreates an immutable list that cannot be modified.Step 2: Compare options
UsevalwithlistOfbecause it creates an immutable list and reference. usesvalandlistOf, ensuring both the reference and list contents cannot change, which matches the requirement.Final Answer:
UsevalwithlistOfbecause it creates an immutable list and reference. -> Option AQuick Check:
val + listOf = fully immutable list [OK]
- Using var with mutableListOf when immutability is needed
- Confusing mutableListOf with listOf
- Thinking val allows list content changes
Ready to prove it?
Pass the test and this pattern moves unknown
