Extensions vs member functions priority in Kotlin - Performance Comparison
When Kotlin runs code with both extensions and member functions, it decides which one to use first.
We want to understand how this choice affects the time it takes to run the code.
Analyze the time complexity of the following code snippet.
class Example {
fun greet() = "Hello from member"
}
fun Example.greet() = "Hello from extension"
fun main() {
val e = Example()
println(e.greet())
}
This code shows a class with a member function and an extension function with the same name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling the function
greet()on an object. - How many times: Only once in this example, but the rule applies every time the function is called.
Each time the function greet() is called, Kotlin checks if a member function exists first.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls to greet(), each directly calls member function |
| 100 | 100 calls to greet(), each directly calls member function |
| 1000 | 1000 calls to greet(), each directly calls member function |
Pattern observation: The time grows linearly with the number of calls, as each call directly invokes the member function.
Time Complexity: O(n)
This means the time to run grows directly with how many times you call the function.
[X] Wrong: "Extension functions run faster than member functions because they are outside the class."
[OK] Correct: Kotlin always calls member functions first if they exist, so calling a member function is direct and not slower than an extension.
Understanding how Kotlin chooses between member and extension functions shows your grasp of function calls and helps you write clear, predictable code.
What if the extension function had a different name than the member function? How would the time complexity change?