0
0
Kotlinprogramming~5 mins

Delegation vs inheritance decision in Kotlin - Performance Comparison

Choose your learning style9 modes available
Time Complexity: Delegation vs inheritance decision
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

Each print call results in one delegated print call, so the work grows directly with the number of calls.

Input Size (n)Approx. Operations
1010 print calls, 10 delegated calls
100100 print calls, 100 delegated calls
10001000 print calls, 1000 delegated calls

Pattern observation: The number of operations grows linearly with the number of print calls.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows directly in proportion to how many times the method is called.

Common Mistake

[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.

Interview Connect

Understanding how delegation and inheritance affect the number of operations helps you explain design choices clearly and confidently in interviews.

Self-Check

What if the delegated method itself contained a loop over input data? How would that change the time complexity?