Delegation vs inheritance decision in Kotlin - Performance Comparison
When choosing between delegation and inheritance, it's important to understand how the program's work grows as it uses these techniques.
We want to see how the cost of running code changes with input size depending on delegation or 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 printer = DelegatingPrinter(realPrinter)
printer.print()
}
This code uses delegation to forward the print call to another object.
Look for loops, recursion, or repeated calls that affect performance.
- Primary operation: The print() method call is forwarded once per call.
- How many times: Each print() call triggers exactly one delegated print() call.
Each print call results in one delegated print call, so the work grows directly with the number of calls.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls, 10 delegated calls |
| 100 | 100 print calls, 100 delegated calls |
| 1000 | 1000 print calls, 1000 delegated calls |
Pattern observation: The number of operations grows linearly with the number of print calls.
Time Complexity: O(n)
This means the time to complete grows directly in proportion to how many times the method is called.
[X] Wrong: "Delegation adds extra hidden loops or slows down the program exponentially compared to inheritance."
[OK] Correct: Delegation simply forwards calls one-to-one without extra loops, so it does not increase the number of operations beyond the calls made.
Understanding how delegation and inheritance affect the number of operations helps you explain design choices clearly and confidently in interviews.
What if the delegated method itself contained a loop over input data? How would that change the time complexity?