Extensions resolved statically in Kotlin - Time & Space 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?
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 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).
As the list size grows, the number of times the extension function runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 20 (2 prints per item x 10 items) |
| 100 | 200 (2 prints x 100 items) |
| 1000 | 2000 (2 prints x 1000 items) |
Pattern observation: The total work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run the code grows linearly with the number of items in the list.
[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.
Understanding how Kotlin extensions work helps you explain performance clearly and confidently in interviews.
"What if the extension function called another function that loops over the string characters? How would the time complexity change?"