0
0
Kotlinprogramming~5 mins

Extensions resolved statically in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Extensions resolved statically
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with Kotlin extensions changes as the input grows.

Specifically, how does the static resolution of extensions affect the number of operations?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


fun String.printTwice() {
    println(this)
    println(this)
}

fun main() {
    val list = listOf("a", "b", "c")
    for (item in list) {
        item.printTwice()
    }
}
    

This code defines an extension function on String and calls it for each item in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the list and calling the extension function for each string.
  • How many times: Once for each item in the list (n times).
How Execution Grows With Input

As the list size grows, the number of times the extension function runs grows the same way.

Input Size (n)Approx. Operations
1020 (2 prints per item x 10 items)
100200 (2 prints x 100 items)
10002000 (2 prints x 1000 items)

Pattern observation: The total work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run the code grows linearly with the number of items in the list.

Common Mistake

[X] Wrong: "Extension functions add extra overhead each time because they are resolved dynamically at runtime."

[OK] Correct: Kotlin resolves extension functions statically, so calling them inside a loop does not add extra hidden cost beyond the loop itself.

Interview Connect

Understanding how Kotlin extensions work helps you explain performance clearly and confidently in interviews.

Self-Check

"What if the extension function called another function that loops over the string characters? How would the time complexity change?"