Why delegation avoids inheritance in Kotlin - Performance Analysis
We want to see how using delegation instead of inheritance affects the time it takes for a program to run.
Specifically, how does the program's work grow when it uses delegation compared to inheritance?
Analyze the time complexity of the following Kotlin code using delegation.
interface Printer {
fun print()
}
class RealPrinter : Printer {
override fun print() {
println("Printing document")
}
}
class DelegatingPrinter(private val printer: Printer) : Printer by printer
fun main() {
val realPrinter = RealPrinter()
val delegatingPrinter = DelegatingPrinter(realPrinter)
delegatingPrinter.print()
}
This code shows a class using delegation to pass print calls to another class instead of inheriting from it.
Look for repeated actions that affect time.
- Primary operation: Calling the
print()method through delegation. - How many times: Each call to
print()is forwarded once to the real printer.
Each print call goes through delegation once, so the work grows directly with how many times print() is called.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls forwarded once each |
| 100 | 100 calls forwarded once each |
| 1000 | 1000 calls forwarded once each |
Pattern observation: The number of operations grows directly with the number of calls, no extra repeated work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of method calls, without extra overhead from delegation.
[X] Wrong: "Delegation adds a lot of extra work compared to inheritance because it calls methods twice."
[OK] Correct: Delegation forwards calls directly once, so it does not double the work. It just passes the call along efficiently.
Understanding how delegation affects time helps you explain design choices clearly and shows you know how code structure impacts performance.
"What if the delegated method called another delegated method inside? How would that affect the time complexity?"