0
0
Kotlinprogramming~5 mins

Safe call operator (?.) in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Safe call operator (?.)
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each name is checked once with the safe call operator, which is a quick null check.

Input Size (n)Approx. Operations
10About 10 null checks and length retrievals
100About 100 null checks and length retrievals
1000About 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.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of items in the list.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we replaced the safe call operator with a manual if-check inside the loop? How would the time complexity change?"