Elvis operator (?:) for default values in Kotlin - Time & Space Complexity
We want to see how using the Elvis operator affects the speed of code when handling values that might be missing.
How does the time to get a value change as the input changes?
Analyze the time complexity of the following code snippet.
fun getLength(text: String?): Int {
return text?.length ?: 0
}
fun processList(list: List): List {
return list.map { getLength(it) }
}
This code gets the length of each string in a list, using 0 if the string is null.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the list with
map. - How many times: Once for every element in the list.
Each item in the list is checked once to get its length or default to zero.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 length checks |
| 100 | 100 length checks |
| 1000 | 1000 length checks |
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 with the list size.
[X] Wrong: "Using the Elvis operator makes the code run faster or slower depending on input size."
[OK] Correct: The Elvis operator just picks a value quickly; it does not add loops or extra work that grows with input size.
Understanding how simple operators like Elvis affect performance helps you write clear and efficient code, a skill valued in real projects and interviews.
"What if we replaced the list.map with a nested loop over a list of lists? How would the time complexity change?"