Safe call operator (?.) in Kotlin - Time & Space Complexity
We want to understand how using the safe call operator affects the time it takes for code to run.
Specifically, does checking for null with ?. change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
fun printNameLength(name: String?) {
val length = name?.length
println(length)
}
fun printAllLengths(names: List) {
for (name in names) {
printNameLength(name)
}
}
This code prints the length of each name in a list, safely handling null names using the safe call operator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each name in the list.
- How many times: Once for each item in the list (n times).
Each name is checked once with the safe call operator, which is a quick null check.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 null checks and length retrievals |
| 100 | About 100 null checks and length retrievals |
| 1000 | About 1000 null checks and length retrievals |
Pattern observation: The work grows directly with the number of names. More names mean more checks, but each check is simple and fast.
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: "Using the safe call operator makes the code slower by a lot because it adds extra checks inside the loop."
[OK] Correct: The safe call operator adds only a simple null check per item, which is very fast and does not change the overall growth pattern.
Understanding how small language features like the safe call operator affect performance helps you write clear and efficient code, a skill valued in many coding discussions.
"What if we replaced the safe call operator with a manual if-check inside the loop? How would the time complexity change?"