Nullable types with ? suffix in Kotlin - Time & Space Complexity
We want to understand how using nullable types with the ? suffix affects the time it takes for a program to run.
Specifically, does checking for null add extra work as the input grows?
Analyze the time complexity of the following code snippet.
fun printLengths(strings: List) {
for (str in strings) {
if (str != null) {
println(str.length)
} else {
println("Null string")
}
}
}
This code goes through a list of strings that can be null and prints their length or a message if null.
- Primary operation: Looping through each item in the list once.
- How many times: Exactly once per item in the list.
As the list gets bigger, the program checks each item once, whether it is null or not.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and prints |
| 100 | About 100 checks and prints |
| 1000 | About 1000 checks and prints |
Pattern observation: The work grows directly with the number of items. More items mean more checks and prints.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items in the list.
[X] Wrong: "Checking for null makes the program slower in a way that depends on how many nulls there are."
[OK] Correct: The program always checks each item once, no matter if it is null or not. The number of nulls does not change how many times it checks.
Understanding how nullable types affect performance helps you write clear and efficient Kotlin code, a useful skill in many coding situations.
What if we replaced the list with a nested list of nullable strings? How would the time complexity change?